Understanding csv DictWriter syntax in python

I looked at a very useful answer to the previous SO question which can be found here when trying 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 the list of headers for the csv file.

The code worked fine, which is nice, but I don’t understand why I had to explicitly reference the base instance of writer to write keyList (headers). I tried this line as write.writerow(keyList) and it did not work. I'm curious why this is so, I can better understand how Python DictWriter works.

Is there a cleaner / better way to write this?

+6
source share
1 answer

It looks like you are relying on undocumented behavior. The DictWriter object DictWriter not have an "official" writer method.

the correct way to output CSV headers is to call

 write.writeheader() 
+3
source

Source: https://habr.com/ru/post/948449/


All Articles