在Python中重命名文件时出现'错误2
我正在尝试批量重命名一个文件夹里的PDF文件。
if len(self.toLoc.get()) == 0:
searchRev = "_R" + newRev
for filename in os.listdir(App.pdfDir):
sep = searchesri
rest = filename.split(sep, 1)[0] + searchRev
os.rename(filename, rest)
else:
searchRev = "_R" + newRev + fromLocation + toLocation
print searchRev
但是当我运行这个程序时,它给我报错了。
File "F:\TOOLS\PythonTools\VCR.py", line 411, in renameMaps
os.rename(filename, rest)
WindowsError: [Error 2] The system cannot find the file specified
不过我可以在循环里打印出文件名,并且能看到结果……
1 个回答
2
os.rename
这个函数需要文件的 完整 路径,但 os.listdir
只会返回文件的名字。
你可以使用 os.path.join
来生成 os.rename
所需要的完整路径:
os.rename(os.path.join(App.pdfDir, filename), rest)