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?
dirs = []
rebinds the local name dirs
. You can modify the contents of the list instead eg. like this:
dirs[:] = []
Try one of following
dirs[:] = []
OR
del dirs[:]
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.