排除 os.walk 中的特定文件夹和子文件夹



列出当前目录中具有分机.txt的所有文件。

L = [txt for f in os.walk('.') 
for txt in glob(os.path.join(file[0], '*.txt'))]

我想避免来自一个特定目录及其子目录的文件。假设我不想深入研究folder3及其可用的子目录来获取.txt文件。我在下面试过

d = list(filter(lambda x : x != 'folder3', next(os.walk('.'))[1]))

但进一步的步骤无法弄清楚。如何包括两者以协同工作?

编辑

我尝试将提供的链接引用为已回答的查询,但我无法获得所需的输出,并且令人惊讶的是将空列表作为a的输出

a=[]
for root, dirs, files in os.walk('.'):
dirs[:] = list(filter(lambda x : x != 'folder3', dirs)) 
for txt in glob(os.path.join(file[0], '*.txt')): 
a.append(txt)

以下解决方案似乎有效,排除集中指定的任何目录都将被忽略,扩展集中的任何扩展都将被包含。

import os
exclude = set(['folder3'])
extensions = set(['.txt', '.dat'])
for root, dirs, files in os.walk('c:/temp/folder', topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]
files = [file for file in files if os.path.splitext(file)[1] in extensions]
for fname in files:
print(fname)

此代码使用选项topdown=True来修改文档中指定的目录名称列表:

当自上而下为 True 时,调用方可以就地修改目录列表 (也许使用 del 或切片赋值(,而 walk(( 只会递归 进入名称保留在目录中的子目录;这可以是 用于修剪搜索

最新更新