简体   繁体   English

将列表转换为CSV格式时如何解决编码错误?

[英]How to fix a encoding error when converting list to csv format?

I'm getting the AttributeError: 'tuple' object has no attribute 'encode'" when trying to write my unicode lists into a csv file: 尝试将我的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'))

Originally (without the .encode('utf-8')) I was getting the error: 最初(没有.encode('utf-8')),我得到了错误:

"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? 有人知道如何解决此问题,以便我可以写我的列表吗?

'tuple' object has no attribute 'encode' 'tuple'对象没有属性'encode'

You can only encode strings (specifically, Unicode strings to byte strings). 您只能编码字符串(特别是将Unicode字符串转换为字节字符串)。

rowToken isn't a string, it's a list of strings. rowToken不是字符串,而是字符串列表。 You have to encode each string inside it individually. 您必须分别编码其中的每个字符串。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM