os.walk walks too much

Tim Peters tim.one at comcast.net
Wed Feb 25 08:52:49 EST 2004


[Marcello Pietrobon]
> I am using Pyton 2.3
> I desire to walk a directory without recursion
>
> this only partly works:
> def walk_files() :
>     for root, dirs, files in os.walk(top, topdown=True):
>         for filename in files:
>             print( "file:" + os.path.join(root, filename) )
>         for dirname in dirs:
>              dirs.remove( dirname )
> because it skips all the subdirectories but one.

Mutating a container while iterating over the container is usually a recipe
for consfusion.  You do need to mutate dirs, but the right way to empty it
here is a one-liner:

    del dirs[:]

or

    dirs[:] = []


> this *does not* work at all
> def walk_files() :
>     for root, dirs, files in os.walk(top, topdown=True):
>         for filename in files:
>             print( "file:" + os.path.join(root, filename) )
>         dirs = []

That doesn't *mutate* (the value bound to) dirs, it just rebinds (the local
name) dirs to an entirely new object, so has no effect on the list of
directory names os.walk() gave to you (it's the list object that matters,
not the name).





More information about the Python-list mailing list