簡體   English   中英

Python:將頂行中的標題附加到 CSV 文件

[英]Python: Appending headers in top row to CSV files

我正在運行將新數據共同添加到現有 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)

有沒有辦法構造上面的代碼以將新標題附加到第0行? 非常感謝所有幫助。

簡單的文件和字符串處理:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM