0

i have some encoding issuse when writing to csv file

how can i fix it

import csv


a = [s.encode('utf-8') for s in a]
f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)

Error

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    a = [s.encode('ascii') for s in a]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128)

How to make program work and write it to csv file?

Mounarajan
  • 1,357
  • 5
  • 22
  • 43
  • Possible duplicate of [How to write UTF-8 in a CSV file](http://stackoverflow.com/questions/18766955/how-to-write-utf-8-in-a-csv-file) – jeff carey Sep 12 '16 at 04:43
  • That looks like it might be information about a real person? Might be better to obscure personal details – jeff carey Sep 12 '16 at 04:44

2 Answers2

0

I ran your code and it works without throwing any errors. Only thing is that your csv file contains byte encoded values. Values with a b' at the front. Is this what you were trying to accomplish? I am using python 3.5.2 .

In the event you do not want byte encoded data just remove the

a = [s.encode('utf-8') for s in a]

And it should work. Here is the output of your data into the csv when I ran it on my machine.

http://puu.sh/r8ksr/d778437622.png

Xavid Ramirez
  • 216
  • 2
  • 7
0
# encoding=utf8  
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')
Mounarajan
  • 1,357
  • 5
  • 22
  • 43