這是我第一次使用堆棧溢出,所以很抱歉,如果我犯了一個錯誤。os.rename無法爲某個目錄重命名文件
當試圖運行這段代碼時,它會正常執行並給我正確重命名的文件。
import os
a = 0
name_target = raw_input("input the prefix of the files you want enumerated")
for filename in os.listdir("."):
if filename.startswith(name_target):
a = int(a) + 1
a = str(a)
no = filename.__len__() - 4
os.rename(filename, filename[:no] + a + '.txt')
現在,只要腳本存在於與文件相同的文件夾中,就可以了。但我希望能夠將這個腳本與不在同一個文件夾中的文件一起使用。
我發現os.listdir('\some\folder\elsewhere')
工作正常,其他目錄,但是當它與os.rename
代碼中斷給我的消息,對其進行重命名:
Traceback (most recent call last):
File "<string>", line 244, in run_nodebug
File "C:\Users\guy\Desktop\otherfolder\renaming_script.py", line 10, in <module>
os.rename(filename, filename[:no] + a + '.txt')
WindowsError: [Error 2] The system cannot find the file specified`
我不知道這裏有什麼問題,請幫助我。
對於重命名,您還必須提供完整路徑,而不僅僅是文件名 – sshashank124
@andi:請通知用戶不正確的Windows標記,而不是僅僅編輯它。 – ChiefTwoPencils