1

How can I get csv.writer.writerow 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]
    writer.writerow(rowPrinter[x])
Community
  • 1
  • 1
Lucas Crostarosa
  • 1,192
  • 6
  • 13
  • 26

1 Answers1

0

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]])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321