2011-11-16 74 views
9

我试图重命名目录中的所有图片。我需要为文件名添加几个预先挂起的零。我是Python的新手,我写了下面的脚本。无法解决WindowsError:[错误2]系统找不到指定的文件

import os 

path = "c:\\tmp" 
dirList = os.listdir(path) 

for fname in dirList: 
    fileName = os.path.splitext(fname)[0] 
    fileName = "00" + fname 
    os.rename(fname, fileName) 
    #print(fileName) 

评论打印行只是为了验证我是在正确的轨道上。当我运行这个时,我得到以下错误,我不知道如何解决它。

Traceback (most recent call last): File "C:\Python32\Code\add_zeros_to_std_imgs.py", line 15, in os.rename(fname, fileName) WindowsError: [Error 2] The system cannot find the file specified

任何帮助,非常感谢。日Thnx。

回答

15

您应该将绝对路径传递给os.rename。现在你只能传递文件名。它没有在正确的地方看。使用os.path.join

试试这个:

import os 

path = "c:\\tmp" 
dirList = os.listdir(path) 

for fname in dirList: 
    fileName = os.path.splitext(fname)[0] 
    fileName = "00" + fname 
    os.rename(os.path.join(path, fname), os.path.join(path, fileName)) 
    #print(fileName) 
相关问题