我试图替换多个子目录中的多个文件中的字符(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

最佳答案

如前所述,您需要为重命名函数提供完整的路径,以使其正常工作:

import os

path = r"C:\Drawings"

for root, dirs, files in os.walk( path ): # parse through file list in the current directory
    for filename in files:
        if "~" in filename:
            source_filename = os.path.join(root, filename)
            target_filename = os.path.join(root, filename.replace("~","_")) # convert spaces to _'s
            os.rename(source_filename, target_filename) # rename the file


最好在路径字符串前添加r,以阻止Python尝试转义反斜杠之后的内容。

关于python - 在Python中使用os.walk,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32380631/

10-14 18:56