0

I am downloading and saving in a CSV data using Django but I have problems when the text is not a simple string but Unicode.

This is what I do:

writer = csv.writer(response)
writer.writerow(tuple(corresponding_data[btn]["columns"].split(',')))
for row in rows:
    writer.writerow(row)
return response

How can I also include unicode text?

EDITED

This is the error I get:

'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)

And if I try this:

writer = csv.writer(response, encoding='utf-8')

I get an error that 'encoding' parameter doesn't exist in this function.

Zulan
  • 21,896
  • 6
  • 49
  • 109
user1919
  • 3,818
  • 17
  • 62
  • 97
  • 1
    In Python 3, use the `encoding` parameter when using `open`, not `csv.writer`. In Python 2, see [this answer](http://stackoverflow.com/a/17245651/235698) for a solution. – Mark Tolonen Jun 14 '16 at 04:36

2 Answers2

2

After lot of searching I managed to solve the issue by doing the following:

for row in rows:
       field_1 = row[0]
       field_2 = row[1].encode(encoding='UTF-8')
       fields = [field_1, field_2]
       writer.writerows([fields])

Explanation: The first column of the CSV contains numbers. The encoding function doesn't work for numbers. That's why I need to encode only the second column. Then I pass the values in a new list called fields and then I write it in the CSV.

user1919
  • 3,818
  • 17
  • 62
  • 97
-2

You need to change

writer = csv.writer(response)

to

writer = csv.writer(response, encoding='utf-8')
Chris Hawkes
  • 11,923
  • 6
  • 58
  • 68