Problem in directory working

G

Gyoung-Yoon Noh

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. walk.next() 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))
find(fullpath)
else:
yield path

if __name__=='__main__':
#find('/home/myhome'); raise SystemExit()
walk = find('/home/myhome')
for i in walk:
print i.next()
 
P

Peter Otten

Gyoung-Yoon Noh said:
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. walk.next() 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 i.next()

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.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,491
Latest member
mohitk

Latest Threads

Top