Kristoffer
Kristoffer

Reputation: 2024

Encoding issue - 'ascii' codec can't decode byte 0xc3

I have an encoding issue in my Python code. I've tried different ways, but I don't get it to work.

value is ä

with open("result.txt", "a") as myfile:
    myfile.write(value.encode('utf-8'))

The error is: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Upvotes: 1

Views: 2172

Answers (1)

Ishan Bhatt
Ishan Bhatt

Reputation: 10241

You can try codecs module, It is specifically designed for that only. I am also hoping that value is unicode not string. If it's a unicode.

import codecs
value = u'ä'
with codecs.open("result.txt", "a", encoding="utf-8") as f:
    f.write(value)

This should do it.

But looking at the error unicode decode it seems your value is string. If its a string

f.write(value.decode("utf-8"))

Always remember unicode is encoded to string, string decoded to unicode. So in your case while writing you encode a string which is not true. But python allows it. So it tries to decode the string to unicode So that it can be encoded further. But surely it would fail as decode would use by default ASCII encoding and ä doesn't fall into that.

Upvotes: 1

Related Questions