Python fnmatch 过滤器用于包含子目录的模式

标签 python path

我正在尝试使用 fnmatch 过滤器来查找给定模式的文件。但是,如果我的模式类似于 subdir/t*.txt 我的代码

for path, subdirs, files in os.walk(root):
    for fn in fnmatch.filter(files, pattern):
        print 'found match'

永远不会到达打印语句。据我所知,它永远找不到匹配项,因为 files 只是基本名称,并且不包含子目录。有没有一种好方法来匹配包含子目录的模式?不过,它仍然适用于像 *.txt 这样的模式。

我能想到的唯一解决方案很笨重,有很多 if 语句和额外的 for 循环(即检查模式是否是路径) ,然后从子目录创建所有可能的路径,然后使用 fnmatch 检查)。想知道是否有一个优雅的解决方案。提前致谢。

最佳答案

如果您在模式中包含前导通配符,则可以通过使 fnmatch.filter() 将每个文件的完整路径与包含子目录的时间进行比较,如图所示。由于这样做需要更多的处理,因此可能值得检查是否有必要,如图所示。

root = ...
pattern = '*/subdir/subdir2/t*.txt'  # note leading wildcard character

if not os.path.dirname(pattern):  # no subdirectories in pattern
    # no need to compare full paths
    for path, subdirs, files in os.walk(root):
        for fn in fnmatch.filter(files, pattern):
            print('found match - path: "{}", fn: "{}"'.format(path, fn))
else:
    for path, subdirs, files in os.walk(root):
        # must compare full file paths to pattern when it contains directories
        filepaths = (os.path.join(path, file) for file in files)  # generator
        for fp in fnmatch.filter(filepaths, pattern):
            fn = os.path.basename(fp)
            print('match found - path: "{}", fn: "{}"'.format(path, fn))

关于Python fnmatch 过滤器用于包含子目录的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33000770/

相关文章:

python - 改进 Django 搜索

python - Django 1.2 等效于 QuerySet.query.as_sql()

python setup.py install 更改脚本解释器

linux - 如何设置 bashrc bash_profile

linux - 确定shell程序中的相对路径还是绝对路径

javascript - 在 JavaScript 中格式化路径字符串

python - 为什么 Python 将元组作为向量添加到列表理解中,但将它们与 '+' 运算符连接起来?

python - 开机后自动运行 python 脚本?

Python - 从长路径获取文件名

python - 在一个 lambda 函数中转换两个 for 循环方法