newbie : prune os.walk

Peter Hansen peter at engcorp.com
Thu Mar 10 08:24:46 EST 2005


Rory Campbell-Lange wrote:
> Hi. How can I list root and only one level down? I've tried setting dirs
> = [] if root != start root, but it doesn't work. 

It sounds like you are trying to take advantage of the feature
described in the docs where "the caller can modify the dirnames
list in-place (perhaps using del or slice assignment)".

Note that what you've tried to do is neither of these, but
instead you are *rebinding* the local name "dirs" to a
completely new list.  This doesn't work, as you've seen.

To modify dirs in-place, you need to do some kind of
slice assignment or del on a slice:

    del dirs[:]

or

    dirs[:] = []

This operates on the same list object rather than creating
a new one, and should get you where you want to be.

Note that this distinction is covered by some of the FAQ
entries, which you might want to read.

-Peter



More information about the Python-list mailing list