os.walk bug?
Tim Peters
tim.peters at gmail.com
Thu Dec 16 15:02:33 EST 2004
[Gabriel Cosentino de Barros]
...
> for root, dirs, files in os.walk('t:\'):
> # -- do stuff
> print "working on", root
> # -- stuff done
>
> print 'DEBUG: dirs =', dirs
> for d in dirs:
> # -- remove archive
> if d[:2] == '20':
> print "--- removing:", d
> dirs.remove(d)
You're mutating a list while iterating over it. This has odd effects.
They're defined in the Language Reference Manual, but it's best to
avoid them. Change
for d in dirs:
to
for d in dirs[:]:
and you should stop getting surprised. That avoids surprise by
iterating over a copy of the list. Then it doesn't matter that you
mutate the original list inside the loop.
More information about the Python-list
mailing list