I've tried many solutions to add a header to my csv file, but nothing's working properly. Here they are :
I used the writerow method, but my data are overwriting the first row.
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?
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? Use shift-cmd-H to add new header for current editing file.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With