Daniel Hutchinson
Daniel Hutchinson

Reputation: 165

Python: Appending headers in top row to CSV files

I'm running scripts that collectively adds new data to an existing CSV file, and I'd like to append additional headers as that new data is added. For example, the following is the structure of the original CSV:

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

I'd like to add additional headers, like this:

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

The code below adds the headers, but just appends the headers to the end of the file.

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)

Is there a way to structure the code above to append the new headers to row 0? All help greatly appreciated.

Upvotes: 1

Views: 896

Answers (1)

Edo Akse
Edo Akse

Reputation: 4391

Simple file & string handling:

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)

Upvotes: 3

Related Questions