Problem in directory working

Peter Otten __peter__ at
Sun Jan 11 10:18:52 CET 2004

Gyoung-Yoon Noh wrote:

> I've written Unix's find-like function using recursive os.listdir()
> call and generator expression. It seems that error happens in
> generator expression.
> Below codes do not work. generates StopIteration.
> When I replace 'yield' with 'print', it works fine.
> Why this does not work?
> I've had successively implemented unix-find using os.path.walk().
> But I want to combine recursive call and generator expressions.
> Any comments are welcome.
> [snip]
> import os
> def find(path):
>     if not os.path.exists(path):
>         raise StopIteration
>     if os.path.isdir(path):
>         for l in os.listdir(path):
>             fullpath = os.sep.join((path, l))
              for p in find(fullpath):
                  yield p
>     else:
>         yield path
> if __name__=='__main__':
>     #find('/home/myhome'); raise SystemExit()
>     walk = find('/home/myhome')
>     for i in walk:
>         print

Just writing find(somepath) will create a new generator but only yield a
value when its next() method is called. This is done implicitly by the for
loop I inserted into your code. Do you know about 2.3's new os.walk()? It
would make a good building block for routines scanning the file system.


More information about the Python-list mailing list