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

Python读取txt写入csv并为空列填充默认N/A的实现问题

问题分析

你的原始代码存在三个核心问题导致输出不符合预期:

  • 没有暂存当前Section名称,读到Section行就直接换行写入,导致Section和对应的Input/Output拆分到不同行,无法匹配表头的三列结构
  • 每读到一行Input或Output就单独写一行,没有对齐到对应列
  • 没有做空值判断逻辑,无法给无输入输出的Section自动填充N/A
最小改动实现方案

几乎保留你原有代码的逻辑框架,仅新增3个临时变量做状态缓存即可,修改后代码如下:

with open('iteration.csv', 'w') as writer:
    flag = False
    writer.write ('Section,Input,Output'+'\n')
    # 新增三个临时变量:当前处理的Section名、暂存的Input值、标记当前Section有没有写入过记录
    current_section = ''
    tmp_input = ''
    has_record = False

    for eachline in open('iteration.txt').readlines():

        if 'Section' in eachline:
            # 遇到新Section前,先处理上一个Section的剩余未写入数据
            if flag and current_section:
                # 有没配对的Input,补Output为N/A
                if tmp_input:
                    writer.write(f"{current_section},{tmp_input},N/A\n")
                    tmp_input = ''
                # 上一个Section完全没有记录,补全N/A行
                elif not has_record:
                    writer.write(f"{current_section},N/A,N/A\n")
            # 重置状态,读取新Section名
            flag = True
            current_section = eachline.split()[-1].strip()
            has_record = False

        if flag:
            if 'Input' in eachline:
                # 先判断是不是有遗留的Input没配对,有就先补N/A写入
                if tmp_input:
                    writer.write(f"{current_section},{tmp_input},N/A\n")
                tmp_input = eachline.strip()
            if 'Output' in eachline and tmp_input:
                # 凑齐一组就写入一行
                writer.write(f"{current_section},{tmp_input},{eachline.strip()}\n")
                tmp_input = ''
                has_record = True
    # 循环结束后处理最后一个Section的剩余数据
    if current_section:
        if tmp_input:
            writer.write(f"{current_section},{tmp_input},N/A\n")
        elif not has_record:
            writer.write(f"{current_section},N/A,N/A\n")
输出效果

运行后得到的iteration.csv内容如下,完全符合需求:

Section,Input,Output
Section_A_Iterating,Input-> 101,Output-> 010
Section_A_Iterating,Input-> 320,Output-> 321
Section_B_Extracting,N/A,N/A
Section_C_Iterating,Input->011,Output-> 011

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:36:02