首页 > 解决方案 > Python:将顶行的标题附加到 CSV 文件

问题描述

我正在运行将新数据共同添加到现有 CSV 文件的脚本,并且我想在添加新数据时附加其他标题。例如,以下是原始 CSV 的结构:

user_id,    text,   text_number
0,  test text A,    text_0
1,      
2,      
3,      
4,      
5,  test text B,    text_1

我想添加额外的标题,如下所示:

user_id,    text,   text_number, field_1, field_2, field_3, field_4
0,  test text A,    text_0
1,      
2,      
3,      
4,      
5,  test text B,    text_1

下面的代码添加了标头,但只是将标头附加到文件的末尾。

import csv  

header = ["field_1", "field_2", "field_3", "field_4"]

with open('test.csv', 'a', encoding='UTF8') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

有没有办法构造上面的代码以将新标题附加到 row 0?非常感谢所有帮助。

标签: pythoncsv

解决方案


简单的文件和字符串处理:

with open('input.csv') as infile:
    text = infile.read()


header = ["field_1", "field_2", "field_3", "field_4"]
with open('output.csv', 'w') as outfile:
    # join the headers into a string with commas and add a newline
    outfile.write(f"{','.join(header)}\n") 
    outfile.write(text)


推荐阅读