Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a Header for CSV file?

Tags:

python

csv

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

I am importing data from a .csv file which has two columns of data, each containing float numbers. Example:

  11   22
  33   44
  55   66

Now I want to add a header for both columns like:

 ColA  ColB
  11    22
  33    44
  55    66

I have tried this:

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

I used 'a' to append the data, but this added the values in the bottom row of the file instead of the first row. Is there any way I can fix it?

like image 644
Sakil Chowdhury Avatar asked Jan 27 '15 02:01

Sakil Chowdhury


People also ask

How do I put a header in a CSV file?

Method #1: Using header argument in to_csv() method. Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method.

How do I add a column header to a CSV file in Python?

Use pandas. DataFrame. read_csv(file, header=None) . Then, call pandas. DataFrame. to_csv(file, header=str_list, index=False) with a string list of column labels as str_list to write a header to the CSV file.

Can CSV files have headers?

From those guidelines and giving the lack of standardization, the header line is optional in a CSV file. When present, the header line must be the first line in the file and must contain the same number of fields as the records. Header and records lines must use the same field delimiters.


2 Answers

One way is to read all the data in, then overwrite the file with the header and write the data out again. This might not be practical 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)
like image 104
Mark Tolonen Avatar answered Sep 27 '22 20:09

Mark Tolonen


i think you should use pandas to read the csv file, insert the column headers/labels, and emit out the new csv file. assuming your csv file is comma-delimited. 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')
like image 29
adrianX Avatar answered Sep 27 '22 18:09

adrianX