如何在将列表转换为csv格式时修复编码错误?

时间:2015-10-27 00:33:10

标签: python list csv unicode encoding

尝试将我的unicode列表写入csv文件时,我得到了AttributeError: 'tuple' object has no attribute 'encode'"

with open('assignmentTest.csv', 'wb') as finale:
writer = csv.writer(finale) #creates csv file to write final lists into
finalRows = zip(firstName, lastName, phdName, universityName, departmentName) #put all of the lists into another lists so that the outputs are in 'column form' as opposed to rows
for rowToken in finalRows: #puts each element of each list together in the same order
    conver = rowToken
    writer.writerow(conver.encode('utf-8'))

最初(没有.encode('utf-8'))我收到错误:

"UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 24: ordinal not in range(128)"

任何人都知道如何解决此问题,以便我可以编写我的列表吗?

1 个答案:

答案 0 :(得分:1)

  

'tuple'对象没有属性'encode'

您只能对字符串进行编码(特别是Unicode字符串到字节字符串)。

rowToken不是字符串,而是字符串列表。您必须单独编码其中的每个字符串。例如:

encodedCells = [cell.encode('utf-8') for cell in rowToken]
writer.writerow(encodedCells)