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

Ron*_*nyA 2 python lambda python-2.7 python-3.x

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

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

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

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

but further steps not able to figure it out.How to include both to work together?

EDIT:

I tried referring the link provided as already answered query but I am unable to get desired output with below and surprisingly getting empty list as output for 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)
Run Code Online (Sandbox Code Playgroud)

Ism*_*sma 6

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

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)
Run Code Online (Sandbox Code Playgroud)

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

当 topdown 为 True 时,调用者可以就地修改 dirnames 列表(可能使用 del 或 slice 赋值),并且 walk() 只会递归到名称保留在 dirnames 中的子目录;这可以用来修剪搜索