本文介绍了当将列表转换为csv格式时如何解决编码错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将我的unicode列表写入csv文件时, AttributeError:'tuple'对象没有属性'encode'
打开('assignmentTest.csv','wb')作为结尾:
writer = csv.writer(finale)#creates csv文件将最终列表写入
finalRows = zip(firstName,lastName,phdName,universityName,departmentName)#将所有列表输出到另一个列表中,以便输出以列形式而不是行
for rowToken in finalRows:#puts每个列表的每个元素以相同的顺序排列
conver = rowToken
writer.writerow(conver.encode('utf-8'))
原来(没有.encode('utf-8'))我得到错误:
UnicodeEncodeError:'ascii'编解码器无法在位置24编码字符u'\\\–':序数不在范围(128)
任何人都知道如何解决这个问题,所以我可以写我的列表?
解决方案
您只能对字符串(特别是Unicode字符串到字节字符串)进行编码。
rowToken
isn '字符串,它是一个字符串列表。你必须单独编码其中的每个字符串。例如:
encodedCells = [cell.encode('utf-8')for rowToken]
writer .writerow(encodedCells)
I'm getting the AttributeError: 'tuple' object has no attribute 'encode'"
when trying to write my unicode lists into a csv file:
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'))
Originally (without the .encode('utf-8')) I was getting the error:
"UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 24: ordinal not in range(128)"
Anyone know how to fix this so I can write my lists?
解决方案
You can only encode strings (specifically, Unicode strings to byte strings).
rowToken
isn't a string, it's a list of strings. You have to encode each string inside it individually. For example:
encodedCells = [cell.encode('utf-8') for cell in rowToken]
writer.writerow(encodedCells)
这篇关于当将列表转换为csv格式时如何解决编码错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!