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

Python输出文件追加行时部分行丢失的问题排查

问题分析与修复方案

你的代码之所以丢失连续的id:行,核心问题在于:只有当存储成员的temp列表不为空时,才会把上一个id行写入输出。但遇到连续的id:行时,前一个id行对应的temp是空的,这部分写入逻辑不会触发,导致这些行被直接覆盖,最终只有最后一个连续的id行被保留。

修复后的代码

import os

def grouping():
    try:
        output = []
        temp = []
        currIdLine = ""
        with open('usergroups.csv', 'r') as f:
            for line in map(str.strip, f):
                if not line:
                    continue
                if line.startswith('uuid'):
                    output.append(line)
                    continue
                if line.startswith('id:'):
                    # 只要缓存过前一个id行,不管有没有成员都先写入输出
                    if currIdLine:
                        output.append(f"{currIdLine};{''.join(temp)}")
                        temp.clear()
                    currIdLine = line
                else:
                    temp.append(line)
        # 处理最后一个未写入的id行
        if currIdLine:
            output.append(f"{currIdLine};{''.join(temp)}")
        
        with open('usergroup.csv', 'w') as f1:
            f1.write('\n'.join(output) + '\n')
        
        print("处理完成,结果已写入usergroup.csv")        
        if os.path.isfile('usergroups.csv'):
            os.remove('usergroups.csv')
          
    except Exception as e:
        print(f"处理失败:{str(e)}")        

grouping()

关键调整说明

  1. 修复核心逻辑:将原来判断temp是否为空的条件,改为判断currIdLine是否不为空——只要已经缓存了上一个id行,不管有没有对应的成员,都先写入输出,避免连续id行被跳过。
  2. 简化代码写法:用map(str.strip, f)替代逐行调用strip,用f-string拼接字符串更简洁,批量写入文件比逐行write更高效。
  3. 增强排错能力:捕获异常时打印具体错误信息,方便快速定位问题。
  4. 适配输出需求:把','.join(temp)改成''.join(temp),匹配你示例里成员直接拼接的格式(如果需要逗号分隔改回即可)。

修复后运行代码,就能得到你期望的输出:

uuid;UserGroup;Name;Description;Owner;Visibility;Members
id:;group1;raji;xyzabc;ramya;public;abcdefgeh
id:;group2;ram;xyzabc;mitu;public;
id:;group3;ram;xyzabc;mitu;public;
id:;group4;raji;rtyui;ramya;private;cvbnmhpoi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:50:16