help needed on generator
Mike C. Fletcher
mcfletch at rogers.com
Wed May 8 22:46:02 EDT 2002
First, the generator problem:
You are ignoring the results of the recursive calls to dirtree (which is
a generator that yeilds at most one result at the moment). You want to
yeild the result of the dirtree, but that's supposed to be a generator,
so you actually want to do:
for result in dirtree( os.path.join(root, dirname), predicate):
yield result
Second the library-function problem:
os.path.isdir() requires a fully-specified path or one relative to the
current working directory.
HTH,
Mike
8<____________ walk.py ___________
#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.
directories = [
dir for dir in os.listdir(root)
if os.path.isdir(os.path.join(root,dir))
]
for dirname in directories:
if predicate(dirname):
for result in dirtree(os.path.join(root, dirname), predicate):
yield result
if __name__ == '__main__':
try:
root = sys.argv[1]
except IndexError:
root = os.getcwd()
for dir in dirtree(root):
print dir
Gonçalo Rodrigues wrote:
> 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
--
_______________________________________
Mike C. Fletcher
http://members.rogers.com/mcfletch/
More information about the Python-list
mailing list