I have a list with some special characters, for which I want to write it tabulated as csv.
My current code is this ans I get UnicodeDecodeError as shown below.
import csv
a = [
['A', 'B', 'C'],
[u'\xDF', u'\xDC', u'\xD8'],
[u'\xC7', u'\xBF', u'\xC9'],
[u'\xA9', u'\xA5', u'\xf3'],
]
with open("out.csv", 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for i in range(0,2):
print a[i]
writer.writerows([a[i]])
...
['A', 'B', 'C']
[u'\xdf', u'\xdc', u'\xd8']
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xdf' in position 0: ordinal not in range(128)
>>>
I've tried modifying a little bit the with open()..
like this
with open("out.csv", 'w') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for row in a:
srow = []
for e in row:
srow.append(e.encode('utf-8'))
writer.writerows(srow)
and within the out.csv I get this:
A
B
C
Ã,Ÿ
Ã,œ
Ã,˜
Ã,‡
Â,¿
Ã,‰
Â,©
Â,¥
Ã,³
while my goal is to get an output like this:
A,B,C
ß,Ü,Ø
Ç,¿,É
©,¥,ó
How can I do this? Thanks in advance