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

如何逐两行读取CSV文件、合并字段并写入新CSV文件?

解决CSV文件两行合并为单行并提取指定字段的问题

以下是满足需求的完整实现代码,包含所有缺失的必要配置和逻辑修正:

import csv

# newline='' 要求Python 3版本
with open('test.csv', 'r', encoding='utf-8') as input_file, \
     open('output.csv', 'w', encoding='utf-8', newline='') as output_file:
    
    # 创建CSV读写对象
    reader = csv.reader(input_file)
    writer = csv.writer(output_file)
    
    # 读取原表头并生成新表头
    original_header = next(reader)
    new_header = original_header + ['price2']
    writer.writerow(new_header)
    
    # 循环读取两行数据并合并写入
    while True:
        try:
            # 读取第一行数据
            first_row = next(reader)
            # 读取第二行数据
            second_row = next(reader)
            
            # 合并:第一行保留所有字段,添加第二行的price1作为price2
            merged_row = first_row + [second_row[3]]
            writer.writerow(merged_row)
        except StopIteration:
            # 无更多数据时终止循环
            break

关键说明

  • 编码要求:确保输入输出CSV文件均为UTF-8编码,指定encoding='utf-8'可避免编码不兼容导致的乱码或读取失败问题。
  • Python版本适配:newline=''参数仅在Python 3中有效,用于避免写入CSV时自动生成多余空行。
  • 表头一致性:基于原表头自动添加price2字段作为新表头,保证输出CSV的表头与合并后的数据字段完全匹配。
  • 索引修正:原输入CSV的字段索引为date(0), name(1), qt(2), price1(3),你的现有代码存在索引错误,本方案已修正该问题,确保读取正确的字段内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:25:19