某無聊的下午的一個小需求ide
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)想要根據文件內容重命名來着.....spa
結果智障了半個小時,沒關閉文件就想rename...........3d
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)