在 Python 中使用 os.walk

Using os.walk in Python

我正在尝试替换多个子目录(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 试图转义反斜杠后面的内容。