6

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?

Community
  • 1
  • 1
user139014
  • 1,445
  • 2
  • 19
  • 33

1 Answers1

3

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()
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • this make sense, but how do I specify the headers for the writeheader function? When I tried to pass keyList in the code `write.writeheader(keyList)` it threw `TypeError: writeheader() takes exactly 1 argument (2 given)` – user139014 Jul 01 '13 at 06:20
  • 1
    @kg41: You don't need to - you specified the headers when building the `DictWriter` object. `.writeheader()` is called without parameters (the single argument is the implicit `self`). – Tim Pietzcker Jul 01 '13 at 06:21
  • Ignore me, I'm being an idiot. Just called `writeheader()` with no argument and it worked. Thanks @Tim. – user139014 Jul 01 '13 at 06:22