这是我第一次使用堆栈溢出,所以很抱歉,如果我犯了一个错误。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