Python中的错误';s os.步行?

Python中的错误';s os.步行?,python,Python,os.walk文档(?highlight=os.walk#os.walk)说,我可以通过从目录列表中删除不需要的目录来跳过遍历它们。文档中的明确示例: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum(getsize(join(root, name)) for name

os.walk
文档(?highlight=os.walk#os.walk)说,我可以通过从目录列表中删除不需要的目录来跳过遍历它们。文档中的明确示例:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories
我看到了不同的行为(使用ActivePython 2.6.2)。即守则:

>>> for root,dirs,files in os.walk(baseline):
...     if root.endswith(baseline):
...             for d in dirs:
...                     print "DIR: %s" % d
...                     if not d.startswith("keep_"):
...                             print "Removing %s\\%s" % (root,d)
...                             dirs.remove(d)
...
...     print "ROOT: %s" % root
...
我得到输出:

DIR: two
Removing: two
DIR: thr33
Removing: thr33
DIR: keep_me
DIR: keep_me_too
DIR: keep_all_of_us
ROOT: \\mach\dirs
ROOT: \\mach\dirs\ONE
ROOT: \\mach\dirs\ONE\FurtherRubbish
ROOT: \\mach\dirs\ONE\FurtherRubbish\blah
ROOT: \\mach\dirs\ONE\FurtherRubbish\blah\Extracted
ROOT: \\mach\dirs\ONE\FurtherRubbish\blah2\Extracted\Stuff_1
...

WTF?为什么没有删除
\\mach\dirs\ONE
?它显然不是以“keep_u2;”开头的,因为您在迭代时正在修改列表
dirs
<代码>一个刚刚被跳过,从未被查看过。比较:

>>> a = [1, 2, 3]
>>> for i in a:
    if i > 1:
        a.remove(i)


>>> a
[1, 3]

您没有将其从
dirs
列表中删除。如果你是,你会看到你的“删除”打印出来,不是吗

将目录中d的
更改为列表中d的
(目录)
,以在迭代时安全地从
dirs
列表中删除项目

或者你可以写:

dirs[:] = [d for d in dirs if not d.startswith("keep_")]

他说了什么。请注意,在示例中,他们在迭代
dirs
列表之前正在修改它。@jathanism:他们根本不迭代
dirs
。)不在示例代码中。但我的观点是,假设有人会这样做。您的第一个建议,使用
list(dirs)
有效,但列表理解没有影响任何更改。@Mike:因为
os.walk
引用了原始列表,为了让列表理解工作,您需要执行:
dirs[:]=[d代表目录中的d,如果不是d.startswith(“保留”)]