繁体   English   中英

在 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 尝试转义反斜杠之后的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM