编码csv输出的特殊字符python

时间:2016-04-18 14:57:07

标签: python csv unicode

如何让csv.writer.writerow输出á或è和其他特殊字符沿着相同的行u,n ......等?

我收到了错误消息 UnicodeEncodeError:'ascii'编解码器无法对位置37中的字符u'\ xed'进行编码:序数不在范围内(128)

this文章中尝试了一些无用的建议

rowPrinter = []

while x < y:
     print "Data in at Line " + str(x + 1)
     rowPrinter.append([a[x], b[x], c[x]]])
     x = x + 1   

x = 0

writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
writer.writerow(['a', 'b', 'c'])
while x < y:
    print rowPrinter[x]
    writer.writerow(rowPrinter[x])

1 个答案:

答案 0 :(得分:0)

您需要对您尝试编写的所有数据进行编码:

writer.writerow([sub.encode("utf-8") for sub in rowPrinter[x]])

如果您有混合数据:

writer.writerow([sub.encode("utf-8")  if isinstance(sub, basestring) else sub for sub in rowPrinter[x]])