【问题标题】:Use os.walk to find a folder with specific file extensions under directory tree使用 os.walk 在目录树下查找具有特定文件扩展名的文件夹
【发布时间】:2019-03-07 00:17:55
【问题描述】:

我需要遍历我的所有文件夹以找到具有特定扩展名的文件的文件夹的文件路径(例如,我们会说.txt)。 我不知道该文件夹是在树的顶部还是在底部。

例如,我们开始于:

OneDrive/Documents/project/SourceCode

包含所有 .txt 文件的文件夹可能位于 OneDrive/Documents/project/SourceCode/TxtFiles 中,也可能位于 OneDrive/Documents/project/TxtFiles 中,也可能位于项目文件之外。

如何找到文件路径?我尝试使用os.walk,但我对它的工作原理没有足够的了解。最后,我将所有的.txt 文件放到一个巨大的列表中。

【问题讨论】:

    标签: python filepath glob os.walk directory-tree


    【解决方案1】:

    我会推荐使用pathlib:

    from pathlib import Path
    
    base_path = Path('base/path/to/search/from')
    text_file = next(base_path.glob('**/*.txt'))
    parent_dir = text_file.parent.resolve()
    

    【讨论】:

      【解决方案2】:
      from pathlib import Path
      from pprint import pprint
      import os
      
      def find_files_of_ext(root, ext):
          return [str(Path(dir, file_)) for dir, subdir, files in os.walk(root) for file_ in files if Path(file_).suffix == ext]
      
      
      filepaths = find_files_of_ext('C:/Users/username/OneDrive', '.jpeg' )
      pprint(filepaths)
      

      【讨论】:

        猜你喜欢
        • 2012-04-02
        • 2011-03-10
        • 1970-01-01
        • 1970-01-01
        • 2010-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多