You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解析TXT目录列表文件时如何按关键词排除指定目录行

解决方法

你需要在匹配到目标目录行之后、正式处理该路径前,增加排除关键词的判断,只要路径中包含ATB6或ATB7B就跳过该目录的解析,同时修正了原有代码首次匹配目标目录时的逻辑漏洞,修改后的完整代码如下:

import glob
import os

filesDict = dict()
for file in glob.glob('/foo/bar/catalog/*.txt'):
    with open(os.path.join('/foo/bar/catalog', file), 'r') as openFile:
        path = None
        files = []
        for line in openFile:
            line = line.rstrip()
            if not line.strip():
                if files and (path is not None):
                    filesDict[path] = files
                    path = None
                    files = []
                    continue
            if line.endswith('/ACS/SDU_:') or line.endswith('/ACS/ScienceDataFile:'):
                # 新增排除逻辑:路径包含禁用关键词则跳过该目录
                if 'ATB6' in line or 'ATB7B' in line:
                    path = None
                    continue
                # 先保存上一个目录的结果
                if files and (path is not None):
                    filesDict[path] = files
                # 初始化当前目录的解析参数
                path = line[5:-2]
                files = []
                next(openFile)
                continue
    
            if path:
                if 'manifest' not in line:
                    files.append(line)

    # 保存文件末尾最后一个未存储的目录结果
    if path:
        filesDict[path] = files

逻辑说明

  • 当匹配到两类目标目录的行时,先检查当前行(即完整目录路径)是否包含要排除的ATB6、ATB7B关键词
  • 如果包含排除关键词,直接将path置为None跳过后续处理,该目录不会被加入结果字典
  • 只有不包含排除关键词的合法目标目录才会进入后续的文件列表读取流程

内容的提问来源于stack exchange,提问作者stickmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:57:04