【发布时间】:2015-09-03 16:10:04
【问题描述】:
我正在尝试替换多个子目录中的多个文件中的一个字符(大约 50 个子文件夹中的 700 多个文件)。如果我删除路径并将文件放在特定文件夹中,则此文件有效;但是,当我尝试使用 os.walk 函数遍历所有子目录时,出现以下错误:
[Error 2] The system cannot find the file specified
它指向我的代码的最后一行。这是完整的代码:
import os
path = "C:\Drawings"
for root, dirs, files in os.walk( path ): # parse through file list in the current directory
for filename in files: #os.listdir( path ):
if filename.find("~"):# > 0: # if a space is found
newfilename = filename.replace("~","_") # convert spaces to _'s
os.rename(filename,newfilename) # rename the file
【问题讨论】:
-
您的
filename是相对的。您需要使用os.path.join(root, filename)。newfilename也是如此。
标签: python os.walk file-not-found