Add header for CSV file?

I am trying to add a header to a CSV file.

I am importing data from a CSV file that has two columns of data, each of which contains floating point numbers. Example:

11 22 33 44 55 66 

Now I want to add a header for both columns, for example:

  ColA ColB 11 22 33 44 55 66 

I tried this:

 with open('mycsvfile.csv', 'a') as f: writer = csv.writer(f) writer.writerow(('ColA', 'ColB')) 

I used 'a' to add data, but this added values ​​to the bottom line of the file instead of the first line. Is there any way to fix this?

+7
python csv
source share
4 answers

One way is to read all the data, and then overwrite the file with a header and write the data again. This may be impractical with a large CSV file:

 #!python3 import csv with open('file.csv',newline='') as f: r = csv.reader(f) data = [line for line in r] with open('file.csv','w',newline='') as f: w = csv.writer(f) w.writerow(['ColA','ColB']) w.writerows(data) 
+10
source share

I think you should use pandas to read the csv file, insert the column headers / labels and release a new csv file. assuming your csv file is comma separated. something like this should work:

  from pandas import read_csv df = read_csv('test.csv') df.columns = ['a', 'b'] df.to_csv('test_2.csv') 
+5
source share

In this case, you do not need a CSV module. You need a fileinput module that allows you to edit in place:

 import fileinput for line in fileinput.input(files=['mycsvfile.csv'], inplace=True): if fileinput.isfirstline(): print 'ColA,ColB' print line, 

In the above code, the print statement will print in the file due to the inplace=True parameter.

0
source share

You can specify the reader names in your code as a list as in your case

  with open('mycsvfile.csv', 'a') as fd: reader = csv.DictReader(fd) reader.fieldnames = ["ColA" , "ColB"] for row in fd 
-one
source share

All Articles