DevEx
DevEx

Reputation: 4561

How to include headers into a csv file

I have a csv file that doesn't include headers. How can I manually add the headers i.e. add the headers to the top of the file

GA, 11
LA, 12
NY, 122
......

Upvotes: 0

Views: 376

Answers (1)

Tejas Pendse
Tejas Pendse

Reputation: 551

As Lutz Horn pointed out, you can use csv.writeheader if you're using py3.2+. If you're using py2.7 like me, maybe this might help:

import csv
myHeaders = ["Header1", "Header2"]
csvData = []
with open( 'myfile.csv','r+b' ) as csvfile:
    # Read the data
    reader = csv.reader(csvfile, quoting=csv.QUOTE_NONE)
    writer = csv.writer(csvfile)
    writer.writerow(myHeaders)
    writer.writerows([row for row in reader])

Note: csv doesn't have an insert/overwrite row method, so you need to read & write the whole data. Should be trivial for small-to-medium sized files

Edit: Previous code would append repeated data to the end of the file

Upvotes: 1

Related Questions