【问题标题】:Find all files with an extension recursively递归查找所有带有扩展名的文件
【发布时间】:2019-11-13 11:36:16
【问题描述】:


我需要对一组 XML 文件执行一些自动化操作。我只是在学习 Python,所以我查找了类似的 SO 答案并想出了这个:

root_dir='/home/user/git/code'
for filename in glob.iglob(root_dir + '**/*.xml', recursive=True):
    print(filename)

上述代码的问题在于它只找到位于“/home/user/git/code”上的顶级 XML 文件,而不是所有嵌套在该文件夹下的 XML 文件。 'recursive' 标志设置为 true,所以我想知道它可能有什么问题...... 任何的想法? 谢谢

【问题讨论】:

  • 你在code 和** 之间忘记了/ 所以你有code** 而不是code/** print(filename)
  • 检查此stackoverflow.com/a/2186565/9563006 btw,根据@furas,只需将root_dir + '**/*.xml' 更改为root_dir + '/**/*.xml' 即可解决您的问题
  • @furas 您应该将其发布为答案而不是评论;)
  • @exhuma 当我在推荐中写它时,我不确定它是否能解决问题:)。但我现在查了一下,我把它作为答案。

标签: python python-3.x


【解决方案1】:

你在code 和** 之间忘记了/,所以你有code** 而不是code/**

最后你需要/

 root_dir='/home/user/git/code/'

或在

开头
'/**/*.xml'

或使用os.path.join() 代替+

os.path.join(root_dir, '**/*.xml')

【讨论】:

  • 感谢您发现错误!
【解决方案2】:

我在自己的项目中无休止地使用此功能。希望它可以为您服务。

import os, glob

def get_files(path, extension, recursive=False):
    """
    A generator of filepaths for each file into path with the target extension.
    If recursive, it will loop over subfolders as well.
    """
    if not recursive:
        for file_path in glob.iglob(path + "/*." + extension):
            yield file_path
    else:
        for root, dirs, files in os.walk(path):
            for file_path in glob.iglob(root + "/*." + extension):
                yield file_path

示例:my_desktop_pdfs = list(get_files('users/xx/Desktop','pdf'))

在你的情况下:

for f in get_files(root_dir, 'xml', recursive=True):
    print(f)

【讨论】:

    【解决方案3】:

    我不知道glob.iglob 但os.walk 应该会产生相同的结果:

    import os
    for root, dirs, files in os.walk('/home/user/git/code'):
        for file in files:
            if (file.endswith('.xml')):
                print(file)
    

    【讨论】:

    • 对于这个用例来说,使用 glob 看起来更简洁。
    猜你喜欢
    • 2011-08-21
    • 2011-06-27
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2010-11-09
    • 1970-01-01
    相关资源
    最近更新 更多