4

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.

1

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

4 Comments

thank you for this answer. It's working, but it is entering an empty row between is row in the updated CSV.
Use with open(filename, "w", newline='') as outfile: if you are in python3
I'm using Python 2.7.14.
Then use with open(filename, "wb") as outfile:
2

A simple solution could be:

import csv

row = ['String', ' String', ' String']

with open('file.csv', 'r') as readFile:
    reader = csv.reader(readFile)
    lines = list(reader)
    lines.insert(1, row)

with open('file.csv', 'w') as writeFile:
    writer = csv.writer(writeFile)
    writer.writerows(lines)

readFile.close()
writeFile.close()

I could not try it. Please let me know if it works.

1 Comment

Thanks, one thing I'm noticing is that this is adding an extra row between each row in the updated CSV.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.