recursing glob
Fredrik Lundh
fredrik at pythonware.com
Thu Feb 15 02:35:44 EST 2001
Grant Griffin wrote:
> Somehow I never am happy with stuff I do with os.walk--is it
> just me?
no.
> 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
</F>
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list