0

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

Ger Cas
  • 2,188
  • 2
  • 18
  • 45
  • have you tried `open("out.csv", 'w',encoding='utf-8')` ? – hack-tramp Jun 06 '20 at 08:01
  • encode using `utf8` – Shijith Jun 06 '20 at 08:01
  • @a'r the thing is I'm using some libraries that work fine currently on python 2 and first need to migrate the code to python 3. – Ger Cas Jun 06 '20 at 08:23
  • @hack-tramp yes, I get the error `TypeError: 'encoding' is an invalid keyword argument for this function` – Ger Cas Jun 06 '20 at 08:31
  • 1
    @GerCas, I understand that this sort of change can be daunting, but Python 2 is no longer supported for bugfixes and - more importantly - for security fixes. So you will need to move over sooner or later. – a'r Jun 06 '20 at 08:32

1 Answers1

0

Try this:

row = [st.encode('utf-8') for st in a[i]]
writer.writerows([row])



Reference: https://stackoverflow.com/a/17246997/4815097

Ombrophile
  • 613
  • 1
  • 7
  • 13