ジェネレーターを使用して各一致を生成し、表現に一致するものをウォークスルーできるようにしたいと思います。これが私が定期的に使用するコードのスニペットです。
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
お役に立てれば。fnmatchをreに置き換えるのはかなり簡単なはずです。