简体   繁体   English

编码csv输出的特殊字符python

[英]encode special characters python for csv output

How can I get csv.writer.writerow to output á or è and other special characters along the same lines u, n....etc? 如何让csv.writer.writerow输出á或è和其他特殊字符沿同一行u,n ......等?

I am getting an error UnicodeEncodeError: 'ascii' codec can't encode character u'\\xed' in position 37: ordinal not in range(128) 我收到错误UnicodeEncodeError:'ascii'编解码器无法编码位置37中的字符u'\\ xed':序号不在范围内(128)

Have tried some of the suggestions in this article with no avail 尝试了本文中的一些建议没有用

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 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])

You need to encode all the data that you are trying to write: 您需要对要写入的所有数据进行编码:

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

If you have a mixture of data: 如果您有混合数据:

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

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

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