12

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?

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Umm - is t a valid open mode ?
@JonClements: I didn't pay attention to the mode; just copied from the OP. Corrected.
TypeError: 'fieldnames' is an invalid keyword argument for this function, I'm using Python 2.6 , PyQt4.7. Can you help?
@Aleksandar: fieldnames is a keyword argument for the csv.DictWriter() and csv.DictReader() classes only. Make sure you don't confuse this with csv.writer() or csv.reader(). Python 2.6 supports it just fine, if you use it correctly.
@Aleksandar: Right, that Python 2.6 doesn't support. The method was added in Python 2.7. You can simulate it with writer.writerow(dict(zip(writer.fieldnames, writer.fieldnames))).
|
2

I encountered a similar problem when writing the CSV file. I had to read the csv file and modify some of the fields in it. To write the header in the CSV file, i used the following code:

reader = csv.DictReader(open(infile))
headers = reader.fieldnames

with open('ChartData.csv', 'wb') as outcsv:
    writer1 = csv.writer(outcsv)
    writer1.writerow(headers)

and when you write the data rows, you can use a DictWriter in the following way

writer = csv.DictWriter(open("ChartData.csv", 'a' ), headers)

In the above code "a" stands for appending.

In conclusion - > use a to append data to csv after you have written your header to the same file

1 Comment

Why create a separate csv.writer() first, then open the same file for appending to with a csv.DictWriter()? Just use writer = csv.DictWriter(outcsv, fieldnames=headers), then writer.writeheader().

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.