Reputation: 161
I am trying to save output from a module to CSV file and I got an error when I ran the following code, which is a part of a 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 headings.)
return self.writer.writerow(self._dict_to_list(rowdict))
TypeError: 'str' does not support the buffer interface
I dont' even understand what the error message is about. I use Python 3.3 and Windows 7.
Thanks for your time.
Upvotes: 4
Views: 6433
Reputation: 19241
Opening a file in binary mode to write csv data to doesn't work in Python 3, simply put. What you want is to open in text mode and either use the default encoding or specify one yourself, i.e., your code should be written like:
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, due to a bug, you also need to specify newline=''
when opening this file for writing the CSV output.
Upvotes: 6