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”开头的。在
因为您在迭代列表
dirs
时修改了它。ONE
只是被跳过了,永远不会被人看到。比较:您不会将其从
dirs
列表中删除。如果你是,你会看到你的“删除”打印件,不是吗?在将
for d in dirs
更改为for d in list(dirs)
,以便在迭代dirs
列表时安全地删除该列表中的项。在或者你可以写:
相关问题 更多 >
编程相关推荐