Reputation: 1720
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.
Upvotes: 3
Views: 307
Reputation: 21289
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')
Upvotes: 5
Reputation: 85492
You need to encode your string. Try this:
f.write(u'Río Negro'.encode('utf-8'))
Upvotes: 4