Assume I have a csv.DictReader object and I want to write it out as a CSV file. How can I do this?
I know that I can write the rows of data like this:
dr = csv.DictReader(open(f), delimiter='\t')
# process my dr object
# ...
# write out object
output = csv.DictWriter(open(f2, 'w'), delimiter='\t')
for item in dr:
output.writerow(item)
But how can I include the fieldnames?
Edit:
In 2.7 / 3.2 there is a new
writeheader()method. Also, John Machin’s answer provides a simpler method of writing the header row.Simple example of using the
writeheader()method now available in 2.7 / 3.2:Instantiating DictWriter requires a fieldnames argument.
From the documentation:
Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you’d write the header and data to a file.
Note:
withstatement was added in 2.6. If using 2.5:from __future__ import with_statementAs @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.: