I was looking at the very helpful answer to a previous SO question which can be found here when attempting to write a list of dicts to a CSV file. The code I used was:
with open((filename), 'wb') as outfile:
write = csv.DictWriter(outfile, keyList)
write.writer.writerow(keyList)
write.writerows(data)
where keyList is a list of headers for the csv file.
The code worked great, which is nice, but I don't understand why I had to explictly call the underlying writer
instance to write the keyList (the headers). I tried that line as write.writerow(keyList)
and it didn't work. I'm curious why that is so I can better understand how Python's DictWriter works.
Is there a cleaner/nicer way of writing this?
Python CSV DictWriter The csv. DictWriter class operates like a regular writer but maps Python dictionaries into CSV rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow method are written to the CSV file.
Using the CSV LibraryThe open() method takes two arguments of type string . First the file name, and second a mode argument. We are using r for read, however this can be omitted as r is assumed by default. We then iterate over all the rows.
The technical difference is that writerow is going to write a list of values into a single row whereas writerows is going to write multiple rows from a buffer that contains one or more lists.
encode('utf-8') filename = 'output. csv' reader = unicode_csv_reader(open(filename)) try: products = [] for field1, field2, field3 in reader: ...
You appear to be relying on undocumented behavior. A DictWriter
object doesn't have an "official" writer
method.
The correct way to output the CSV headers is to call
write.writeheader()
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