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

标签 python python-3.x python-2.7 lambda

列出当前目录下所有扩展名为.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 修改在 docs 中指定的目录名称列表。 :

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search

关于python - 排除 os.walk 中的特定文件夹和子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51954665/

相关文章:

python - Shebang 不适用于 python3

python - 打印没有换行符python

python - 任何人都可以帮助我解决我在 Python 2.7 中不断遇到的 TypeError 问题吗?

python - Flask SQLAlchemy 未获取更改的记录

python - 将 python3 设为我在 Mac 上的默认 python

python - 如何拆分列表元素?

macos - Python 虚拟环境,Py2app 构建,wxpython 错误

python - 定点 Z3 中的解释

python - 使用 PyPlot 绘制平滑线,然后设置标记

python - Spotipy 尝试使用 oauth 进行验证