Python的错误步行手术?

2024-06-26 07:03:15 发布

您现在位置:Python中文网/ 问答频道 /正文

os.walk文档(http://docs.python.org/library/os.html?突出显示=操作系统。步行操作系统.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

我看到了不同的行为(使用ActivePython2.6.2)。即代码:

^{pr2}$

我得到输出:

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
...

世贸基金会?为什么\\mach\dirs\ONE没有删除?它显然不是以“keep”开头的。在


Tags: in文档osdirrootfilesonewalk
2条回答

因为您在迭代列表dirs时修改了它。ONE只是被跳过了,永远不会被人看到。比较:

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


>>> a
[1, 3]

您不会将其从dirs列表中删除。如果你是,你会看到你的“删除”打印件,不是吗?在

for d in dirs更改为for d in list(dirs),以便在迭代dirs列表时安全地删除该列表中的项。在

或者你可以写:

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

相关问题 更多 >