本节的实战例子为利用Python来批量移除照片文件名中含有的数字
1. 在写程序前,首先还是先列出程序大致的流程图:
step 1:获得文件名
step 2:对每一个文件进行重新命名
2. 下载需要重新命名的44张照片,地址为:点击打开链接
3. 在idle中创建 renamefile.py ,然后创建一个同样名字的函数,并将要实现的功能进行注释
def renamefiles():
#(1) get filenames from a folder
#(2) for each file,rename filename
renamefiles()
4. 现在开始具体实现,根据 明确需求-google it 原则,google需要的信息(而不是为了一个点去学一个面,这也是入门某种技术时需要避免的)
file_list=os.listdir(r"G:\Programs\Python\prank")google:find file names in a folder in python
我们得到:
os.listdir()
will get you everything that's in a directory - files and directories.接下来利用前面所学:定义os函数:import os 使用listdir函数:listdir() 其中括号内为照片文件夹路径,为了让Python直接按照字符串的方式解读地址,地址“”前需要加r ,然后将此函数的输出存入一个变量中,并打印输出
print file_list
5. 接下来进行第二步,通过阅读Python文档,了解os函数中哪个函数可以进行文件的重命名
地址为https://docs.python.org/2/library/os.html
找到
rename
(src,dst)函数,src参数为原文件名,dst为预期文件名为了实现对文件名的更改,google到了translate函数,其具体用法及示例如下:
str.translate(table[, deletechars]);
Parameters
table -- You can use the maketrans() helper function in the string module to create a translation table.
deletechars -- The list of characters to be removed from the source string.
Return Value
This method returns a translated copy of the string.
Example
The following example shows the usage of translate() method. Under this every vowel in a string is replaced by its vowel position −
#!/usr/bin/python
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab)
When we run above program, it produces following result −
th3s 3s str3ng 2x1mpl2....w4w!!!
Following is the example to delete 'x' and 'm' characters from the string −
#!/usr/bin/python
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab, 'xm')
This will produce following result −
th3s 3s str3ng 21pl2....w4w!!!
6.完整的代码如下:
import os
def renamefiles():
#(1) get filenames from a folder
file_list=os.listdir(r"G:\Programs\Python\prank")
#print (file_list)
saved_path = os.getcwd()
print("Current working directory is"+saved_path)
os.chdir(r"G:\Programs\Python\prank")
#(2) for each file,rename filename
for file_name in file_list:
os.rename(file_name,file_name.translate(None,"0123456789"))
print("old name: "+file_name)
print("new name: "+file_name.translate(None,"0123456789"))
renamefiles()
7.注:其中oslistdir是为了显示当前工作目录,os.chdir函数是为了将程序的工作目录改为想要操作的目录,两个Print是为了输出原文件名和修改后的文件名。
8.注意还使用了for循环来进行循环更改。
9.入门一门技术,想要一次学会所有是不可能的,并且也不可能记住,因此使用时实时检索,现学现用的能力十分重要。因此,查看官方文档并加以适当的练习是快速入门的捷径。
10. 推荐网站:https://docs.python.org/2/index.html
以及很好的在线学习教程网站:https://www.tutorialspoint.com/index.htm