Python批量重命名

某无聊的下午的一个小需求

1 import os
2 dirPath = r''    #路径
3 format = r''    #后缀
4 name = 0
5 for file in os.listdir(dirPath):
6     oldPath = '%s\%s'%(dirPath, file)
7     newPath = '%s\%s.%s'%(dirPath, name, format)
8     name += 1
9     os.rename(oldPath, newPath)
......

 

然后今晚(20160729)想要根据文件内容重命名来着.....

结果智障了半个小时,没关闭文件就想rename...........

 1 import os
 2 import re
 3 
 4 rootpath = r'' #路径
 5 
 6 paten = r'(?<=Title:\n).*' #按照需求写正则
 7 os.chdir(rootpath) #脚本和文件们不在同一个文件夹是需将当前路径改一下
 8 
 9 for i in os.listdir(rootpath):
10     oldname = os.path.normpath(os.path.join(rootpath, i))
11     file = open(i, 'r')
12     try:
13         newname = re.findall(paten, file.read())[0] + '.txt'
14         newname = os.path.normpath(os.path.join(rootpath, newname))
15         file.close() #先关闭再rename
16         os.rename(oldname, newname)
17     except IndexError as e: #有一个文件是跟其他不同的....在try的下一行产生IndexError
18         file.close() #记得关闭文件......
19         print(i)
View Code

 

posted @ 2016-07-07 15:51  book丶book丶  阅读(157)  评论(0编辑  收藏  举报