Simply put, the following code:
f.write(u'Río Negro')
raises the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 1: ordinal not in range(128)
What can I do?
I'm using Python 2.7.3.
Simply put, the following code:
f.write(u'Río Negro')
raises the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 1: ordinal not in range(128)
What can I do?
I'm using Python 2.7.3.
Using open from the codecs module will eliminate the need for you to manually encode:
import codecs
with codecs.open('file.txt', 'w', encoding='utf-8') as f:
f.write(u'Río Negro')
In Python 3, this functionality is built in to the standard open function:
with open('file.txt', 'w', encoding='utf-8') as f:
f.write(u'Río Negro')
open() built-in.io.open() should be used instead of codecs.open(). Its behavior is the same as open() on Python 3 (where io.open is open).You need to encode your string. Try this:
f.write(u'Río Negro'.encode('utf-8'))
f is a binary file ('wb' mode on Python 3).