recursing glob
Grant Griffin
not.this at seebelow.org
Thu Feb 15 22:58:36 EST 2001
Fredrik Lundh wrote:
>
> Grant Griffin wrote:
> > Somehow I never am happy with stuff I do with os.walk--is it
> > just me?
>
> no.
In retrospect, I think os.walk would be a lot friendlier if it passed
two arguments to its function instead of one. (When I first began with
Python, I didn't realize that that "one" argument could be a list or a
tuple.)
>
> > Anyway, does anybody have any ideas on how to recurse glob
> > more elegantly?
>
> define "more elegantly" ;-)
>
> the following involves more library code, but is much
> easier to use.
>
> (reposted)
>
> From: "Fredrik Lundh" <effbot at telia.com>
> Subject: Re: glob
> Date: Wed, 10 May 2000 09:35:43 +0200
>
> > Is there a recursive glob?
>
> no, but you can easily roll your own using os.path.walk
> and the fnmatch module.
>
> or you can use this iterator class, adapted from an example
> in the eff-bot library guide (see below):
>
> #
> # adapted from os-path-walk-example-3.py
>
> import os
> import fnmatch
>
> class GlobDirectoryWalker:
> # a forward iterator that traverses a directory tree
>
> def __init__(self, directory, pattern="*"):
> self.stack = [directory]
> self.pattern = pattern
> self.files = []
> self.index = 0
>
> def __getitem__(self, index):
> while 1:
> try:
> file = self.files[self.index]
> self.index = self.index + 1
> except IndexError:
> # pop next directory from stack
> self.directory = self.stack.pop()
> self.files = os.listdir(self.directory)
> self.index = 0
> else:
> # got a filename
> fullname = os.path.join(self.directory, file)
> if os.path.isdir(fullname) and not os.path.islink(fullname):
> self.stack.append(fullname)
> if fnmatch.fnmatch(file, self.pattern):
> return fullname
>
> for file in GlobDirectoryWalker(".", "*.py"):
> print file
Cool! Thanks.
I think that's definitely more elegant than what I did:
def glob_recurse(args, dirname, names):
""" args[0] = pattern, args[1] = file list """
args[1] += glob.glob(os.path.join(dirname, args[0]))
and then:
os.path.walk('.', glob_recurse, [pattern, file_names])
I think this would have been pretty easy for a more seasoned Pythoneer
to cough up, but it took me awhile. In particular, I tried to pass it a
tuple at first, and it took me awhile to figure out the source of the
error message.
we-horses-don't-always-drink-the-water-we're-lead-to-if-it's-not
-clearly-labeled-as-such-<wink>-ly y'rs,
=g2
--
_____________________________________________________________________
Grant R. Griffin g2 at dspguru.com
Publisher of dspGuru http://www.dspguru.com
Iowegian International Corporation http://www.iowegian.com
More information about the Python-list
mailing list