Reputation: 2173
I am working on a csv file using DictReader and DictWriter.
I tried to work based on the following code found here:
import csv
fieldnames = ['Node', 'ID', 'Test Description', 'file-name',
'module', 'view', 'path1','path2'] # defines order in output file
with open('testdata.txt', 'rb') as csvinput:
with open('testdata2.txt', 'wb') as csvoutput:
csvwriter = csv.DictWriter(csvoutput, fieldnames, delimiter=',')
csvwriter.writeheader()
nodecount = 0
for row in csv.DictReader(csvinput):
nodecount +=1
row['Node'] = 'node %s' % nodecount # add 'Node' entry to row data
csvwriter.writerow(row)
I am using python 3.2 and I get the following error:
File "/usr/lib/python3.2/csv.py", line 153, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
TypeError: 'str' does not support the buffer interface
I read that this error could be due to the fact that "If you use Python3x then string is not the same type as for Python 2.x, you must cast it to bytes (encode it)."
But here, the files are already opened using the 'b' argument (and therefore as binary files) right?
Upvotes: 2
Views: 838
Reputation: 353209
You're using a Python 2 example for the csv
module in Python 3. As you guessed, as part of the str/bytes switch, the required pattern for opening files for the csv
module changed a little bit. (I admit the difference can be a headache, but things make so much more sense in Python 3 than Python 2 that it was worth it.)
As the documentation explains, the new required idiom for opening csv files for reading/writing is
with open('testdata.txt', newline='') as csvinput:
with open('testdata2.txt', 'w', newline='') as csvoutput:
Upvotes: 5