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

如何用Python合并CSV中被反斜杠拆分的同编号连续行

实现方案

思路说明

  • 逐行读取原始文件,拆分每行的行号和内容部分
  • 用字典暂存每个行号对应的拼接内容,自动去重行号
  • 自动移除每行末尾的反斜杠、换行符和多余的空白字符,拼接时自动补充空格避免内容粘连
  • 最后按行号升序输出拼接后的完整行

可运行代码

from collections import defaultdict

# 配置输入输出文件路径
input_path = "EPA.csv"
output_path = "EPA_merged.csv"

# 存储行号对应内容的字典
line_content = defaultdict(str)

with open(input_path, 'r', encoding='utf-8') as f:
    for line in f:
        # 跳过空行
        if not line.strip():
            continue
        # 拆分开头的行号和内容,最多拆分1次避免内容内的空格被切割
        line_num, content = line.split(maxsplit=1)
        # 移除内容末尾的反斜杠、换行符和两端多余空白
        content = content.rstrip('\\\n').strip()
        # 拼接内容,前加空格避免内容粘连
        line_content[line_num] += ' ' + content

# 按行号数字升序排序后输出
with open(output_path, 'w', encoding='utf-8') as f:
    for num in sorted(line_content.keys(), key=lambda x:int(x)):
        # 去掉内容开头多余空格后输出完整行
        f.write(f"{num}{line_content[num]}\n")

注意事项

  • 如果CSV文件使用特殊编码,可将代码中的encoding='utf-8'替换为对应编码,比如gbk
  • 代码会自动跳过文件中的空行,不影响正常拼接逻辑
  • 输出文件默认按照原行号的数字顺序排列,不会出现行号乱序问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 10:36:02