Skip to main content
 首页 » 编程设计

python之os.rename 不工作

2024年09月07日6dflying

我尝试重命名文件。不希望文件以“__”开头。尝试使用帖子中的代码: Removing characters from filename in batch

制作 list 时:

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 

请您参考如下方法:

你应该给出 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)