我正在尝试使用 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/