簡體   English   中英

將列表轉換為CSV格式時如何解決編碼錯誤?

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

嘗試將我的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)"

有人知道如何解決此問題,以便我可以寫我的列表嗎?

'tuple'對象沒有屬性'encode'

您只能編碼字符串(特別是將Unicode字符串轉換為字節字符串)。

rowToken不是字符串,而是字符串列表。 您必須分別編碼其中的每個字符串。 例如:

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