我认为您想使用生成器来生成每个匹配项,以便您可以遍历与您的表达式匹配的内容。这是我经常使用的代码片段。
import os, fnmatch
#
# This wrapper for os.walk is based on Python Cookbook, 2.16.
# Added the exclude_dirs named parameter so that we can skip svn folders.
# Added the yield_files named parameter so that we can return only folders.
#
def walk_file_system (root, patterns='*', single_level=False, yield_folders=False, yield_files=True, exclude_dirs='.svn'):
# Expand patterns from semicolon-separated string to list
patterns = patterns.split (';')
exclude_dirs = exclude_dirs.split (';')
for path, subdirs, files in os.walk (root):
for exclude_dir in exclude_dirs:
for dir in subdirs:
if fnmatch.fnmatch (dir, exclude_dir):
subdirs.remove(dir)
fsnodes = []
if yield_folders:
fsnodes.extend(subdirs)
if yield_files:
fsnodes.extend(files)
fsnodes.sort ( )
for name in fsnodes:
for pattern in patterns:
if fnmatch.fnmatch (name, pattern):
yield os.path.join (path, name)
break
if single_level:
break
你可以像这样使用它。
def walk_file_system_test():
#patterns='*', single_level=False, yield_folders=False, yield_files=True, exclude_dirs='.svn'):
print "Walk current directory with function defaults."
for fsnode in walk_file_system(os.getcwd()):
print fsnode
#patterns='*', single_level=False, yield_folders=True, yield_files=True, exclude_dirs='.svn'):
print "Walk current directory with yield_folders=True."
for fsnode in walk_file_system(os.getcwd(), yield_folders=True):
print fsnode
#patterns='*', single_level=False, yield_folders=True, yield_files=False, exclude_dirs='.svn'):
print "Walk current directory with yield_folders=True, yield_files=False."
for fsnode in walk_file_system(os.getcwd(), yield_folders=True, yield_files=False):
print fsnode
#patterns='*', single_level=False, yield_folders=True, yield_files=False, exclude_dirs='.svn'):
print "Walk current directory with yield_folders=True, yield_files=False, exclude_dirs='.svn;temp'."
for fsnode in walk_file_system(os.getcwd(), yield_folders=True, yield_files=False, exclude_dirs='.svn;temp'):
print fsnode
希望这可以帮助。用 re 替换 fnmatch 应该相当简单。