Posted By

brunns on 03/19/08


Tagged

glob locate fnmatch walk


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

carlosabargues


Locating files throughout a directory tree


 / Published in: Python
 

URL: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499305

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. import os, fnmatch
  2.  
  3. def locate(pattern, root=os.curdir):
  4. '''Locate all files matching supplied filename pattern in and below
  5. supplied root directory.'''
  6. for path, dirs, files in os.walk(os.path.abspath(root)):
  7. for filename in fnmatch.filter(files, pattern):
  8. yield os.path.join(path, filename)

Report this snippet  

You need to login to post a comment.