[Tutor] for loop problems

Gonçalo Rodrigues op73418@mail.telepac.pt
Mon Nov 4 12:06:01 2002


----- Original Message -----
From: "Chris Davidson" <cxd401@psu.edu>

Just three comments about the code:


> Hello tutor mailing list,
>
> I am trying to loop through an output of os.listdir() and when i go
> through and remove elements from the list that have a leading '.' it
> deletes it if i print each element, but when I try to return the list
> after the work to the calling function it seems like it was never
> deleted. I have the variable listDirectory, which is being returned,
> declared outside the loop. Here is the piece of code in question:
>
>
> directory = "/home/chris"
>
> def checkDirectories():
>     listDirectory = os.listdir(directory)
>     listDirectory = listDirectory[:]
>     endingMark = '/'
>
>     for element in listDirectory:

for-looping a list and at the same time altering it's structure (in your
case, removing elements) is *not* a good idea. Really not.

>         pathname = '%s/%s' % (directory, element)

Use os.path.join - don't reinvent the wheel!

>         mode = os.stat(pathname)[ST_MODE]
>         if element.startswith('.'):
>             listDirectory.remove(element)
>             continue
>         if S_ISDIR(mode):
>             endingMark.join(element)

The join method of strings (usually) takes a list as argument. I may be
mistaken, but it seems to me that element is a string. So, while this code
works (because a string is iterable and join works with any iterable) it
might not do what you want...

>             print element
>         elif S_ISREG(mode):
>             print "File: %s" % element
>     return listDirectory
>
> Thank you in advance for any help,
> Chris
>

Although not replying directly to your question hope it helps some, with my
best regards,
G. Rodrigues