Help me understand this iterator
- From: "LaundroMat" <Laundro@xxxxxxxxx>
- Date: 31 Oct 2006 03:36:08 -0800
Hi,
I've found this script over at effbot
(http://effbot.org/librarybook/os-path.htm), and I can't get my head
around its inner workings. Here's the script:
import os
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()
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
for file in DirectoryWalker("."):
print file
Now, if I look at this script step by step, I don't understand:
- what is being iterated over (what is being called by "file in
DirectoryWalker()"?);
- where it gets the "index" value from;
- where the "while 1:"-loop is quitted.
Thanks in advance,
Mathieu
.
- Follow-Ups:
- Re: Help me understand this iterator
- From: Peter Otten
- Re: Help me understand this iterator
- From: Steven D'Aprano
- Re: Help me understand this iterator
- From: Fredrik Lundh
- Re: Help me understand this iterator
- From: Peter Otten
- Re: Help me understand this iterator
- Prev by Date: Re: create global variables?-the full story
- Next by Date: Re: 3d programming without opengl
- Previous by thread: Re: create global variables?-the full story
- Next by thread: Re: Help me understand this iterator
- Index(es):
Relevant Pages
|