首页 > 解决方案 > os.rename 不起作用

问题描述

我尝试重命名文件。不希望文件以“__”开头。尝试使用帖子中的代码: 批量删除文件名中的字符

制作清单时:

myDir = os.listdir(r"S:\Shared\Santa Rosa")
for x in myDir:
  ...

我得到这个输出:

Tuesday
Wednesday
__1831.pdf
__1832.pdf
__1833.pdf
__1834.pdf
__1841.pdf
__1842.pdf
__1843.pdf
__1844.pdf
__1851.pdf
__1852.pdf
__1853.pdf
__1854.pdf
__1861.pdf
__1862.pdf

但是什么时候这样做:

for x in myDir:
    os.rename(x, x.replace('__', ''))

我得到错误:

Traceback (most recent call last):
  File "<interactive input>", line 2, in <module>
WindowsError: [Error 2] The system cannot find the file specified

标签: pythonoperating-systemrename

解决方案


您应该为 os.rename 提供完整的路径名,例如

dirName = r"S:\Shared\Santa Rosa"
myDir = os.listdir(dirName)
for x in myDir:
    oldName = os.path.join(dirName, x)
    newName = os.path.join(dirName, x.replace('__', ''))
    os.rename(oldName, newName)

推荐阅读