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?