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?
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')
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.