Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert new line in CSV at second row via Python

Is it possible to insert a new line in a CSV file at the 2nd row? For example, I have a CSV with column names and their values:

meter_id, sdp_id, lat, lon
813711, 1331, 34.298, -83.113

The application I'm attempting to read this file into requires a new line added indicating the column type. In the above example all would be string, so the CSV would need to be:

meter_id, sdp_id, lat, lon
String, String, String, String
813711, 1331, 34.298, -83.113

I've read several posts how to add a new line at the end of the CSV, but couldn't find anything on how to do the above.

like image 659
J. Skinner Avatar asked Oct 17 '25 14:10

J. Skinner


1 Answers

This is one approach using csv module.

Demo:

import csv
toAdd = ["String", "String", "String", "String"]
with open(filename, "r") as infile:
    reader = list(csv.reader(infile))
    reader.insert(1, toAdd)

with open(filename, "w") as outfile:
    writer = csv.writer(outfile)
    for line in reader:
        writer.writerow(line)
like image 84
Rakesh Avatar answered Oct 19 '25 05:10

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!