os.walk is a very nice replacement for os.path.walk, which I never did feel comfortable with. There's one very common pattern of usage, though, which still benefits from a simple helper-function; locating all files matching a given file-name pattern within a directory tree.
1 2 3 4 5 6 7 8
import os, fnmatch def locate(pattern, root=os.curdir): '''Locate all files matching supplied filename pattern in and below supplied root directory.''' for path, dirs, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename)
An example - I needed to identify all malformed XML files within my project. With the help of locate (and ElementTree) all I needed was:
from xml.parsers.expat import ExpatError import xml.etree.ElementTree as ElementTree for xml in locate("*.xml"): try: ElementTree.parse(xml) except (SyntaxError, ExpatError): print xml, "\tBADLY FORMED!"
Thanks to Marius Gedminas and Tom Lynn for improvements incorporated in this code.