newbie : prune os.walk

  • Thread starter Rory Campbell-Lange
  • Start date
R

Rory Campbell-Lange

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. I clearly don't
understand how the function works. I'd be grateful for some pointers.

Thanks
Rory

/tmp/test
|-- 1
|-- 2
|-- 3
|-- 4
|-- one
| |-- 1
| |-- 2
| |-- 3
| |-- 4
| `-- subone <- dont want to see this
`-- two
|-- 5
|-- 6
|-- 7
`-- 8

3 directories, 12 files
.... print root, dirs, files
....
/tmp/test ['one', 'two'] ['1', '2', '3', '4']
/tmp/test/one ['subone'] ['1', '2', '3', '4']
/tmp/test/one/subone [] []
/tmp/test/two [] ['5', '6', '7', '8']
 
D

Diez B. Roggisch

Untestet:

def foo(base, depth=2):
for root, dirs, files in os.walk(base, True):
if len(root.split(os.sep)) < depth:
yield root, dirs, files

for root, dirs, files in foo("/tmp"):
print root, dirs, files
 
P

Peter Hansen

Rory said:
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
 
S

Scott David Daniels

Rory said:
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. I clearly don't
understand how the function works. I'd be grateful for some pointers.

base = '/tmp/test'
for root, dirs, files in os.walk(base):
if root != base:
dirs[:] = []


--Scott David Daniels
(e-mail address removed)
 
T

Tim Roberts

Rory Campbell-Lange said:
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. I clearly don't
understand how the function works. I'd be grateful for some pointers.

The statement
dir = []
does not actually change the list that was passed in. It creates a NEW
empty list and binds it to "dir".

If you want to empty the "dir" variable, try:
del dir[:]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top