本文介绍了有效地从 os.walk 中删除 dirnames 中的子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在 python 2.7 中的 Mac 上,使用 os.walk 遍历目录时,我的脚本会遍历apps",即 appname.app,因为这些实际上只是它们自己的目录.后来在处理过程中,我在处理它们时遇到了错误.我无论如何都不想浏览它们,因此就我的目的而言,最好忽略这些类型的目录".

On a mac in python 2.7 when walking through directories using os.walk my script goes through 'apps' i.e. appname.app, since those are really just directories of themselves. Well later on in processing I am hitting errors when going through them. I don't want to go through them anyways so for my purposes it would be best just to ignore those types of 'directories'.

这是我目前的解决方案:

So this is my current solution:

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

如您所见,第二个 for 循环将针对子目录的每次迭代运行,这是不必要的,因为第一遍删除了我想要删除的所有内容.

As you can see, the second for loop will run for every iteration of subdirs, which is unnecessary since the first pass removes everything I want to remove anyways.

必须有更有效的方法来做到这一点.有什么想法吗?

There must be a more efficient way to do this. Any ideas?

推荐答案

你可以这样做(假设你想忽略包含 '.' 的目录):

You can do something like this (assuming you want to ignore directories containing '.'):

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

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

The slice assignment (rather than just subdirs = ...) is necessary because you need to modify the same list that os.walk is using, not create a new one.

请注意,您的原始代码不正确,因为您在迭代列表时修改了列表,这是不允许的.

Note that your original code is incorrect because you modify the list while iterating over it, which is not allowed.

这篇关于有效地从 os.walk 中删除 dirnames 中的子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 17:34