I get the following error when try to write in file:
UnicodeEncodeError('ascii', u'B\u1ea7u cua (B\u1ea7u cua 2017 )', 1, 2, 'ordinal not in range(128)'))
I try to write this text Bầu cua in file:
f = codecs.open("13.txt", "a", "utf-8")
f.write("{}\n".format(title))
Also I tried to use title.encode()
It gives me a new error:
When I use .encode(text) I get the following error: `
UnicodeDecodeError('ascii', 'B\xe1\xba\xa7u cua (B\xe1\xba\xa7u cua 2017 )\n', 1, 2, 'ordinal not in range(128)'))
`
2 Answers 2
As described this answer to "Writing Unicode text to a text file?", you have many solutions.
Basically, you have 2 issues:
The str.format() method must be used on an unicode object
u'{}\n'.format('Bầu cua')
The file you write to also must be opened with the right encoding:
f = open('13.txt', 'a', encoding='utf-8')
As a result, this works for Python 3:
data = 'Bầu cua'
f = open('13.txt', 'a', encoding='utf-8')
line = u'{}\n'.format(data)
f.write(line)
f.close()
Try with these two lines at the beginning of the file. It works well for Python2.7
#!/usr/bin/env python
# -*- coding: utf-8 -*-
data = u'Bầu cua'
f = open('test.txt', 'a')
line = u'{}\n'.format(data)
f.write(line.encode('utf8'))
f.close()
http://stackoverflow.com/a/6048203/7041624