Python列出子目录中的所有文件但排除某些目录

标签 python python-3.x glob

我想列出所有 txt目录结构中的文件,但排除某些特定文件夹。

例如我想获取所有 txt

下的文件

D:\_Server\<subfolders>\Temp_1\Config\

D:\_Server\<subfolders>\Temp_1\Config\Stat 但排除

D:\_Server\<subfolders>\Temp_1\Config\Historie\

D:\_Server\<subfolders>\Temp_1\Config\Archive\

为了获取所有文件,我使用了以下代码:

glob.glob('D:\\_Server\\**\\Config\\**\\*.olc', recursive=True)

这会产生所有 txt 的列表文件还有 Archive 中的文件和Historie文件夹。

这对于 Python 来说可能吗 Glob模块?或者有更好的解决方案来存档吗?

最佳答案

您也可以使用os来做到这一点:

import os
extensions = ('.txt')                                    #extinctions want to search
exclude_directories = set(['exclude_directory_name'])    #directory (only names) want to exclude
for dname, dirs, files in os.walk('/root/path/to/directory'):  #this loop though directies recursively 
    dirs[:] = [d for d in dirs if d not in exclude_directories] # exclude directory if in exclude list 
    for fname in files:
        if(fname.lower().endswith(extensions)): #check for extension 
           fpath = os.path.join(dname, fname)   #this generate full directory path for file
           print fpath

关于Python列出子目录中的所有文件但排除某些目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394131/

相关文章:

python - 如何突出显示文本小部件的当前行?

python - 使用Python高效地将SPSS数据写入Excel

Python 简单的反向传播没有按预期工作

python - pandas 数据框中不重叠的滚动窗口

Python 3 unicode 到 utf-8 文件

python - 函数重复十次而不是一次 - Pygame Zero

python - 必须使用 x 实例作为第一个参数调用未绑定(bind)方法 f() (改为使用 str 实例)

java - XML 中的通配 rune 件匹配

node.js - Glob 和 NPM Minimatch : Match all files and directories recursively except for specific directories

node.js - 更漂亮的 glob 匹配多种文件类型