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

Python按规则合并文件行时部分行丢失的问题求助

问题排查与解决:CSV文件中非'ab'行追加到上一行,部分'ab'行丢失

问题原因

你的代码核心逻辑漏洞在于:当遇到新的'ab'开头行时,仅在temp列表不为空的情况下才会将上一行currIdLine写入输出。但对于那些后面没有非'ab'行的'ab'行(比如源文件中的ab;user2、ab;user3),此时temp是空的,代码不会将之前的currIdLine写入输出,直接覆盖为新的'ab'行,导致这部分行最终丢失,仅在循环结束时写入最后一个currIdLine。

修正代码

def grouping():
    output = []
    temp = []
    currIdLine = ""
    with open('usergroups.csv', 'r') as f:
        for lines in f.readlines(): 
            line = lines.strip()
            if not line:
                print("Skipping empty line")
                continue 
            if line.startswith('grpid'): 
                output.append(line)
                continue 
            if line.startswith('ab'):
                # 只要已缓存过'ab'行,就先处理上一行再更新缓存
                if currIdLine:
                    if temp:
                        output.append(f"{currIdLine};{','.join(temp)}")
                    else:
                        output.append(currIdLine)
                    temp.clear()
                currIdLine = line
            else:
                temp.append(line)
    # 处理最后一行缓存的'ab'行
    if currIdLine:
        if temp:
            output.append(f"{currIdLine};{','.join(temp)}")
        else:
            output.append(currIdLine)

    with open('new.csv', 'w') as f1:
        for row in output:
            f1.write(row + '\n')

grouping()

关键修改点

  1. 遇到新的'ab'行时,不再判断temp是否为空,只要currIdLine不为空(即已经缓存过一行'ab'行),就将其写入输出:
    • 如果temp有内容,就追加到currIdLine后写入
    • 如果temp为空,直接写入currIdLine本身
  2. 循环结束后处理最后一行缓存的currIdLine时,同样区分temp是否为空的情况,确保所有行都被写入

运行上述代码后,输出结果将完全符合你的期望。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:35:30