How to fix a encoding error when converting list t

2019-03-06 05:36发布

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?

1条回答
forever°为你锁心
2楼-- · 2019-03-06 06:14

'tuple' object has no attribute 'encode'

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)
查看更多
登录 后发表回答