glob
Fredrik Lundh
effbot at telia.com
Wed May 10 03:40:40 EDT 2000
Douglas Partridge <dpartrid at lawson.appcomp.utas.edu.au> wrote:
> 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