Re: Help me understand this iterator
- From: Peter Otten <__peter__@xxxxxx>
- Date: Tue, 31 Oct 2006 13:02:34 +0100
LaundroMat wrote:
[me hitting send too soon]
Now, if I look at this script step by step, I don't understand:
- where the "while 1:"-loop is quitted.
class DirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
If self.stack is empty, pop() will raise an IndexError which terminates both
the 'while 1' loop in __getitem__() and the enclosing 'for file in ...'
loop
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not
os.path.islink(fullname):
self.stack.append(fullname)
return fullname
The return statement feeds the next file to the for loop.
Peter
.
- References:
- Help me understand this iterator
- From: LaundroMat
- Help me understand this iterator
- Prev by Date: Re: Help me understand this iterator
- Next by Date: concatenating numpy arrays
- Previous by thread: Re: Help me understand this iterator
- Next by thread: concatenating numpy arrays
- Index(es):
Relevant Pages
|