Mixing generators and recursion

Peter Hansen peter at engcorp.com
Tue Nov 4 15:23:14 EST 2003


Gerson Kurz wrote:
> 
> I stumbled upon a behaviour that would be somewhat nice to have, but
> seemingly is not possible (in 2.3 anyway):
> 
> import os, stat
> 
> def walkem(directory):
>     print "Read files in %s" % directory
>     for filename in os.listdir(directory):
>         pathname = os.path.join(directory, filename)
>         if os.path.isdir(pathname):
>             print "Before walkem: %s" % pathname
>             walkem(pathname)
>             print "After walkem: %s" % pathname
>         else:
>             yield pathname
> 
> if __name__ == "__main__":
>     for filename in walkem("<your directory here>"):
>         print filename
> 
> This code will not recurse subdirectories - because the recursive
> walkem() is not called (or so is my interpretation). It is of course
> easy to rewrite this; I was just wondering if someone can enlighten me
> why this happens (the yield documentation doesn't give me any clues),
> and whether this might be a future feature?

Is "directory" an absolute or a relative path?

You don't use any abspath() calls, nor any os.chdir() calls, so I would 
think if "directory" is relative the code won't work properly.

-Peter




More information about the Python-list mailing list