我怀疑您的子目录可能有问题。
如果您的目录包含文件“
a”,“
b”和子目录“
dir”,分别包含文件“
sub+1”和“
sub+2”,则对的调用
os.walk()将产生以下值:
(('.',), ('dir',), ('a', 'b'))(('dir',), (,), ('sub+1', 'sub+2'))当你处理第二元组,你会调用
rename()与
'sub+1', 'sub_1'作为参数,当你想要的是
'dirsub+1','dirsub_1'。
要解决此问题,请将代码中的循环更改为:
for root, dirs, filenames in os.walk(folder): for filename in filenames: filename = os.path.join(root, filename) ... process file here
在执行任何操作之前,它将使用文件名连接目录。
编辑:
我认为以上是正确的答案,但并非完全正确的理由。
假设您
File+1的目录中有一个文件“ ”,
os.walk()将返回
("C:/documents and Settings/DuffA/Bureaublad/Johan/10G304655_1/", (,), ("File+1",))除非您在
10G304655_1目录中,否则在调用时
rename(),
File+1将不在 当前 目录中找到文件“ ”
,因为该目录与
os.walk()正在查找的目录不同。通过对
os.path.join()yuo的调用,告诉重命名为look在正确的目录中。
编辑2
所需代码的示例可能是:
import os# Use a raw string, to reduce errors with characters.folder = r"C:documents and SettingsDuffABureaubladJohan10G304655_1"old = '+'new = '_'for root, dirs, filenames in os.walk(folder): for filename in filenames: if old in filename: # If a '+' in the filename filename = os.path.join(root, filename) # Get the absolute path to the file. print (filename) os.rename(filename, filename.replace(old,new)) # Rename the file


![WindowsError:[错误2]系统找不到指定的文件 WindowsError:[错误2]系统找不到指定的文件](http://www.mshxw.com/aiimages/31/661017.png)
