-->

从os.walk dirnames中有效去除子目录(Efficiently removing sub

2019-06-24 12:29发布

关于Python 2.7通过使用os.walk我的脚本目录行走时的Mac经历“应用”,即appname.app,因为这些都是真的只是自己的目录。 那么以后的处理,通过他们去当我击球失误。 我不希望通过他们去反正所以对于我而言这将是最好只是忽视这些类型的“目录”的。

所以这是我目前的解决方案:

for root, subdirs, files in os.walk(directory, True):
    for subdir in subdirs:
        if '.' in subdir:
            subdirs.remove(subdir)
    #do more stuff

正如你所看到的,第二个for循环将用于子目录的每一次迭代,这是不必要的,因为第一遍消除一切,我想反正删除运行。

必须有这样做更有效的方式。 有任何想法吗?

Answer 1:

你可以这样做(假设你要忽略包含目录“”):

subdirs[:] = [d for d in subdirs if '.' not in d]

切片分配(而不仅仅是subdirs = ... )是必要的,因为你需要修改相同的列表os.walk使用,而不是创建一个新的。

需要注意的是,因为你修改的同时遍历它的名单,这是不允许的原密码不正确。



Answer 2:

也许从这个例子Python文档的os.walk会有所帮助。 它的工作原理从下往上(删除)。

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

我有点困惑你的目标,你想删除一个目录树和遇到的错误,或者是你试图走一棵树,只是想列出简单的文件名(不包括目录名)?



文章来源: Efficiently removing subdirectories in dirnames from os.walk