Skip to content

Instantly share code, notes, and snippets.

@gkalab-snippets
Created September 25, 2012 21:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkalab-snippets/3784557 to your computer and use it in GitHub Desktop.
Save gkalab-snippets/3784557 to your computer and use it in GitHub Desktop.
Python: dirwalk with pattern
import os
import fnmatch
def dirwalk(directory, pattern="*"):
"walk a directory tree, using a generator"
for name in os.listdir(directory):
fullpath = os.path.join(directory, name)
if os.path.isdir(fullpath) and not os.path.islink(fullpath):
for name in dirwalk(fullpath): # recurse into subdir
if fnmatch.fnmatch(name, pattern):
yield name
elif fnmatch.fnmatch(fullpath, pattern):
yield fullpath
if __name__ == "__main__":
for file in dirwalk("c:\\tmp", "*.py"):
print file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment