Lucas Crostarosa Lucas Crostarosa - 1 year ago 188
Python Question

encode special characters python for csv output

How can I get

to output á or è and other special characters along the same lines u, n....etc?

I am getting an error
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 37: ordinal not in range(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

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

Answer Source

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