On Wed, Jun 10, 2009 at 2:28 AM, spir<denis.s...@free.fr> wrote:
> Hello,
>
> A foolow-up ;-) from previous question about glob.glob().
>
> I need to 'glob' files recursively from a top dir (parameter). Tried to use 
> os.walk, but the structure of its return value is really unhandy for such a 
> use (strange, because it seems to me this precise use is typical). On the 
> other hand, os.path.walk seemed to meet my needs, but it is deprecated.
>
> I'd like to know if there are standard tools to do that. And your comments on 
> the 2 approaches below.

I would use os.walk(), with fnmatch.fnmatch() to do the pattern
matching, and write the function as a generator (using yield). It
would look something like this (untested):

import os, fnmatch
def findFiles(topDir, pattern):
  for dirpath, dirnames, filenames in os.walk(topDir):
    for filename in filenames:
      if fnmatch.fnmatch(filename, pattern):
        yield os.path.join(dirpath, filename)

To get a list of matches you would call
  list(findFiles(topDir, pattern))

but if you just want to iterate over the paths you don't need the list.

Kent
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to