列出当前目录下所有扩展名为.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/