如何在python中将unicode列表转换为utf8格式?
我正试图找到一种有效的方法,将列表转换为utf8格式,同时又不会弄乱我的writer.writerowrowToken-基本上就是我用来为列表创建单独的列的方法。@DimitrisJim现在删除的答案是正确的。您是否不小心使用了writerow而不是writerow 以UTF-8编码的输出文件内容:如何在python中将unicode列表转换为utf8格式?,python,list,csv,unicode,Python,List,Csv,Unicode,我正试图找到一种有效的方法,将列表转换为utf8格式,同时又不会弄乱我的writer.writerowrowToken-基本上就是我用来为列表创建单独的列的方法。@DimitrisJim现在删除的答案是正确的。您是否不小心使用了writerow而不是writerow 以UTF-8编码的输出文件内容: #!python2 #coding:utf8 import csv firstName = u'John Joe 马克'.split() lastName = u'Doe Blow 多路能'.s
#!python2
#coding:utf8
import csv
firstName = u'John Joe 马克'.split()
lastName = u'Doe Blow 多路能'.split()
phdName = u'a b c'.split()
universityName = u'd e f'.split()
departmentName = u'g h i'.split()
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
writer.writerow([col.encode('utf8') for col in rowToken])
您是否考虑过只转换每个元素?另外,如果你有一个输入文件,你应该考虑使用那个文件对象作为生成器,而不是把它的内容读入一个列表中,然后它被顺序地处理和写入。为什么你要通过“B”模式来打开?我试着转换每个元素,但是只是相同的错误。在对Windows产生影响的平台上,csv.reader或csv.writer需要b。看。
#!python2
#coding:utf8
import csv
firstName = u'John Joe 马克'.split()
lastName = u'Doe Blow 多路能'.split()
phdName = u'a b c'.split()
universityName = u'd e f'.split()
departmentName = u'g h i'.split()
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
writer.writerow([col.encode('utf8') for col in rowToken])
John,Doe,a,d,g
Joe,Blow,b,e,h
马克,多路能,c,f,i