Jacob Walley
Jacob Walley

Reputation: 33

Ascii codec error when writing ConfigObj

I wonna read/write russian text, for example:

from configobj import ConfigObj
obj = ConfigObj('config.ini')
mydata = ['вася', 'петя']
obj['users'] = mydata
obj.write()

And I get error:

obj.write()
File "/usr/lib/python3.4/site-packages/configobj-5.0.6-py3.4.egg/configobj.py", line 2119, in write
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-13: ordinal not in range(128)

On python 2.7 everything works fine, but 3.4... Help me please. What am I doing wrong?

Upvotes: 3

Views: 547

Answers (2)

TomK
TomK

Reputation: 364

Almost. Because you set a key using a UTF-8 string, your ConfigObj data structure now has a mix of Unicode and UTF-8.

The option default_encoding controls the conversion from UTF-8 to Unicode. Then the option encoding controls the conversion back from Unicode to UTF-8, which is what if finally written to the file.

So, you want:

from configobj import ConfigObj
obj = ConfigObj('config.ini', default_encoding='utf8')
mydata = ['вася', 'петя']
obj['users'] = mydata
obj.write()

Upvotes: 0

tynn
tynn

Reputation: 39873

Before writing the config, the output is encoded if it isn't a binary type already. That's why it works on Python 2.

To handle the encoding correctly, you need to set it accordingly:

obj = ConfigObj('config.ini', encoding='utf8')

Upvotes: 1

Related Questions