help needed on generator
Gonçalo Rodrigues
op73418 at mail.telepac.pt
Wed May 8 21:08:36 EDT 2002
Hi,
I've coded this generator to traverse a directory tree.
#Import generators.
from __future__ import generators
#Import modules.
import os, sys
def true(*args, **kwargs):
"""The identically true function."""
return 1
def dirtree(root, predicate = true):
"""Visit a directory tree, using a generator.
A predicate can be provided to trim the directories visited."""
#Yield root dir.
if predicate(root):
yield root
#Recurse into subdirectories.
for dirname in [dir for dir in os.listdir(root) if
os.path.isdir(dir)]:
if predicate(dirname):
dirtree(os.path.join(root, dirname), predicate)
if __name__ == '__main__':
try:
root = sys.argv[1]
except IndexError:
root = os.getcwd()
for dir in dirtree(root):
print dir
When I feed "C:" to the sucker (run as script) only "C:" gets printed.
Can anyone point out to me what I am doing wrong?
P.S: I want to keep the order: first yield the directory then go and
visit the childs.
Thanks in advance and best regards,
Gonçalo Rodrigues
More information about the Python-list
mailing list