0
我試圖從一個目錄中取出一個文件名,例如'OP 40 856101.txt',刪除.txt,將每個單詞設置爲特定變量,然後重新排列文件名基於「856101 OP 040」等所需的順序。下面是我的代碼:一次在目錄中重命名多個文件
import os
dir = 'C:/Users/brian/Documents/Moeller'
orig = os.listdir(dir) #original names of the files in the folder
for orig_name in orig: #This loop splits each file name into a list of stings containing each word
f = os.path.splitext(orig_name)[0]
sep = f.split() #Separation is done by a space
for t in sep: #Loops across each list of strings into an if statement that saves each part to a specific variable
#print(t)
if t.isalpha() and len(t) == 3:
wc = t
elif len(t) > 3 and len(t) < 6:
wc = t
elif t == 'OP':
op = t
elif len(t) >= 4:
pnum = t
else:
opnum = t
if len(opnum) == 2:
opnum = '0' + opnum
new_nam = '%s %s %s %s' % (pnum,op,opnum, wc) #This is the variable that contain the text for the new name
print("The orig filename is %r, the new filename is %r" % (orig_name, new_nam))
os.rename(orig_name, new_nam)
但是我正在用我最後的for循環的錯誤,我嘗試重命名目錄中的每個文件。
FileNotFoundError: [WinError 2] The system cannot find the file specified: '150 856101 OP CLEAN.txt' -> '856101 OP 150 CLEAN'
的代碼完全運行,直到os.rename()命令,如果我打印出變量new_nam,它打印出的所有目錄中的文件的正確的命名順序。似乎它找不到原始文件,儘管將文件名替換爲new_nam中的字符串。我認爲這是一個目錄問題,但是我對Python更新,似乎無法找到編輯我的代碼的位置。任何提示或建議將不勝感激!
工作!謝謝!! – Bkal05