[Tutor] for loop problems
Sean 'Shaleh' Perry
shalehperry@attbi.com
Mon Nov 4 11:34:02 2002
On Monday 04 November 2002 08:15, Chris Davidson wrote:
> Hello tutor mailing list,
>
> =09I 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:
>
>
a) since you did not declare 'listDirectory' as global the function creat=
es=20
its own, internal variable.
b) instead of endsMark.join(list) you want to use os.path.join(list). No=
need=20
for you to muck about with the directory separator.
c) the more idiomatic approach is to read the directory, process the file=
s and=20
add them to a new list:
items =3D []
for item in os.listdir(directory):
if item[0] =3D=3D '.': # or you can use startswith()
continue
pathname =3D os.path.join(directory, element)
mode =3D os.state(pathname)[ST_MODE]
if S_ISDIR(mode):
print "%s is a directory" % item
elif S_ISREG(mode):
print "%s is a file" % item
items.append(item)
return items