Entry
Is there a recursive glob?
May 10th, 2000 02:32
unknown unknown, Fredrik Lundh
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
-->