0

i am trying to walk a directory tree and exclude certain directories. Now, according to os.walk exclude .svn folders for example i should be able to modify the 'dirs' list which would then let me prune the tree. I tried the following:

import sys
import os

if __name__ == "__main__":

    for root, dirs, files in os.walk("/usr/lib"):
        print root
        dirs = []

I would have expected to not enter ANY subdirectories but i do:

/usr/lib
/usr/lib/akonadi
/usr/lib/akonadi/contact
/usr/lib/akonadi/contact/editorpageplugins
/usr/lib/os-prober
/usr/lib/gnome-settings-daemon-3.0
/usr/lib/gnome-settings-daemon-3.0/gtk-modules
/usr/lib/git-core
/usr/lib/git-core/mergetools
/usr/lib/gold-ld
/usr/lib/webkitgtk-3.0-0
/usr/lib/webkitgtk-3.0-0/libexec

What am i missing?

Community
  • 1
  • 1
matze999
  • 431
  • 1
  • 5
  • 18

3 Answers3

2
dirs = []

rebinds the local name dirs. You can modify the contents of the list instead eg. like this:

dirs[:] = []
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
1

Try one of following

dirs[:] = []

OR

del dirs[:]
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

root gives the entire path and not just the root from where you started.

The docs makes it a bit more clear to what it's doing:

for dirpath, dirnames, filenames in os.walk('/usr/lib'):
    print dirpath

See the docs here

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92