Pat*_*man 6 python os.walk python-2.7
在使用os.walk浏览目录时在python 2.7中的mac上,我的脚本通过'apps'即appname.app,因为这些只是他们自己的目录.以后在处理过程中我遇到了错误.我不想再经历它们,所以为了我的目的,最好只是忽略那些类型的"目录".
所以这是我目前的解决方案:
for root, subdirs, files in os.walk(directory, True):
for subdir in subdirs:
if '.' in subdir:
subdirs.remove(subdir)
#do more stuff
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,第二个for循环将针对每个子目录的迭代运行,这是不必要的,因为第一遍除去了我想要删除的所有内容.
必须有一种更有效的方法来做到这一点.有任何想法吗?
int*_*jay 17
你可以这样做(假设你想忽略包含'.'的目录):
subdirs[:] = [d for d in subdirs if '.' not in d]
Run Code Online (Sandbox Code Playgroud)
切片分配(而不仅仅是subdirs = ...
)是必要的,因为您需要修改os.walk
正在使用的相同列表,而不是创建新列表.
请注意,您的原始代码不正确,因为您在迭代时修改了列表,这是不允许的.
归档时间: |
|
查看次数: |
10249 次 |
最近记录: |