代码之家  ›  专栏  ›  技术社区  ›  Mike Caron

python的os.walk出错?

  •  0
  • Mike Caron  · 技术社区  · 14 年前

    这个 os.walk 文件编制( http://docs.python.org/library/os.html ?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
    ...
    

    世界跆拳道联盟?为什么不是 \\mach\dirs\ONE 远离的?显然不是从“保持”开始的。

    2 回复  |  直到 14 年前
        1
  •  5
  •   SilentGhost    14 年前

    因为你在修改列表 dirs 在它上面迭代。 ONE 只是被跳过了,再也看不到。比较:

    >>> a = [1, 2, 3]
    >>> for i in a:
        if i > 1:
            a.remove(i)
    
    
    >>> a
    [1, 3]
    
        2
  •  2
  •   FogleBird    14 年前

    你不会把它从 dirs 名单。如果你是,你会看到你的“删除”打印出来,不是吗?

    变化 for d in dirs for d in list(dirs) 安全地从 迪尔斯 迭代时列出。

    或者你可以写:

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