I tried to just use the ‘w’ tag while opening the file, but it double spaced the lines which caused the read to not work. So I found that changing to ‘wb’ will be the correct formatting. Now that I am using the ‘wb’ flag I can’t get the csv.writer.writerow() to work. I have encoded all my strings and am lost as to why I keep getting this error. All the questions I see say that b’string here’ or myString.encode(‘ascii’) solves the error I get, but it is not solving it for me. Here is what I have:
dataWriter = csv.writer(open(fileName, 'wb'))
for i in range(self.ui.table.rowCount()):
rowData = [self.ui.table.item(i,0).text().encode('utf-8')\
,self.ui.table.item(i,1).text().encode('utf-8')\
,self.ui.table.item(i,2).text().encode('utf-8')\
,self.ui.table.item(i,3).text().encode('utf-8')\
,self.ui.table.item(i,4).text().encode('utf-8')]
dataWriter.writerow(rowData)
Which I figured would work but it still gives me the following error:
“TypeError: must be bytes or buffer, not str”
on the line “dataWriter.writerow(rowData).
Any help would be apreciated.
Thank you.
You appear to be running Python 3.x. Advice about using binary mode for csv files applies to Python 2.x. The codecs module is not required for 3.x — just use
encoding=whateverwhen you open the file. What is needed for 3.x is that the file be opened withnewline=''. This applies to both reading and writing, although it is not documented for writing (bug report has been submitted). After sorting out your doble-spacing problem, this will work:Contents of output file:
Suggestion: give some consideration to legibility of your code … instead of
try