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

Python日志分割问题:输出文件仅写一行且格式不符求助

日志分割代码问题修复

问题根源

  1. 文件模式错误:每次匹配到日志行时用w+模式打开输出文件,该模式会清空文件原有内容,导致最终每个文件仅保留最后一行匹配的日志
  2. 写入内容错误:将split()拆分后的列表转成字符串写入,输出结果变成列表格式(如['INFO', 'xxx']),而非原始日志文本

修复后的代码

def Fileparse():
    # 同时管理输入日志和三个输出文件,自动处理文件关闭
    with open("logfile.txt", "r") as log_file, \
         open('Info.txt', 'a') as info_file, \
         open('Debug.txt', 'a') as debug_file, \
         open('Error.txt', 'a') as error_file:
        
        for line in log_file:
            stripped_line = line.strip()
            # 跳过空行
            if not stripped_line:
                continue
            # 按行开头判断,直接写入原始行
            if stripped_line.startswith('INFO'):
                info_file.write(line)
            elif stripped_line.startswith('DEBUG'):
                debug_file.write(line)
            elif stripped_line.startswith('ERROR'):
                error_file.write(line)

if __name__=='__main__':
    Fileparse()

优化说明

  • 用with语句批量管理文件,无需手动调用close(),避免资源泄漏
  • 采用a(追加)模式打开输出文件,新内容会附加到文件末尾,不会清空原有内容
  • 用startswith()判断行开头,比split()更健壮(避免空行或格式异常引发的索引错误)
  • 直接写入原始日志行line,完整保留日志的原始格式和内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:48:32