Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a header to a csv file in Python?

Tags:

python

csv

I've tried many solutions to add a header to my csv file, but nothing's working properly. Here they are :

  1. I used the writerow method, but my data are overwriting the first row.

  2. I used the DictWriter method, but I don't know how to fill it correctly. Here is my code:

    csv = csv.DictWriter(open(directory +'/csv.csv', 'wt'), fieldnames = ["stuff1", "stuff2", "stuff3"], delimiter = ';')
    csv.writeheader(["stuff1", "stuff2", "stuff3"])
    

I got a "2 arguments instead of one" error and I really don't know why.

Any advice?

like image 393
Crolle Avatar asked Apr 09 '13 16:04

Crolle


People also ask

How do I put a header in a CSV file?

How do I put a header in a CSV file? If your CSV file doesn't have headers, you can add them by simply creating a new first line in the text file and typing in your headers.

How do you add a header to a file in python?

How do you add a header to a file in python? Use shift-cmd-H to add new header for current editing file.

How do I make a header in Python?

You can create headings by starting and ending a line with up to five equal signs. The heading text is between those markers, separated by a single space.

How do you add a column name to a CSV file in Python?

Copy and paste it in the place of "file name. csv". If the file does not open, try using "\"(double backslash) in place of "\"(single backslash) in the file path. If you do not use "header=None" while reading the file, the data in the first row will be taken as a header.


1 Answers

All you need to do is call DictWriter.writeheader() without arguments:

with open(os.path.join(directory, 'csv.csv'), 'wb') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ["stuff1", "stuff2", "stuff3"], delimiter = ';')
    writer.writeheader()

You already told DictWriter() what your headers are.

like image 107
Martijn Pieters Avatar answered Oct 01 '22 05:10

Martijn Pieters