Error writing CSV in Python 3

I am trying to save the output from a module to a CSV file, and I got an error when I ran the following code, which is part of the module:

base_keys = ['path', 'rDATE', 'cDate', 'cik', 'risk', 'word_count'] outFile = open('c:\\Users\\ahn_133\\Desktop\\Python Project\\MinkAhn_completed2.csv','wb') dWriter = csv.DictWriter(outFile, fieldnames=base_keys) dWriter.writerow(headerDict) 

Here is the error message (base_keys are the headers.)

 return self.writer.writerow(self._dict_to_list(rowdict)) TypeError: 'str' does not support the buffer interface 

I don’t even understand what an error message is. I am using Python 3.3 and Windows 7.

Thank you for your time.

+4
source share
1 answer

Opening a file in binary mode to write csv data does not work in Python 3, just click. You want to open in text mode and either use the default encoding, or specify it yourself, that is, your code should be written as follows:

 import csv k = ['hi'] out = open('bleh.csv', 'w', newline='', encoding='utf8') # mode could be 'wt' for extra-clarity writer = csv.DictWriter(out, k) writer.writerow({'hi': 'hey'}) 

Now, thanks to the bug , you also need to specify newline='' when opening this file to record CSV output.

+6
source

All Articles