简体   繁体   English

带有某些目录的python walk目录树

[英]python walk directory tree with excluding certain directories

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. 现在,根据os.walk排除例如.svn文件夹 ,我应该能够修改'dirs'列表,然后让我修剪树。 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 . 重新绑定了本地名称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. root提供了整个路径,而不仅仅是您开始时的根。

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 在这里查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM