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=whatever
when you open the file. What is needed for 3.x is that the file be opened with newline=''
. 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:
import csv
data = [
['xfforick', 123.456],
['polonius', 987.564],
]
with open('demo.csv', 'w', newline='', encoding='utf8') as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
Contents of output file:
>>> open('demo.csv', 'rb').read()
b'xc3xbforick,123.456
polonius,987.564
'
>>>
Suggestion: give some consideration to legibility of your code ... instead of
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)
try
table = self.ui.table
for i in range(table.rowCount()):
row = [table.item(i, j).text() for j in range(5)]
writer.writerow(row)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…