【问题标题】:Using os.walk in Python在 Python 中使用 os.walk
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢你。这教会了我很多东西并解决了我的问题。
  • 很高兴它解决了您的问题。您也可以单击答案旁边的勾号以接受解决方案。这也会给你一个徽章。
猜你喜欢
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2013-06-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多