José
José

Reputation: 1720

How to write Unicode text into a Python file object

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

Answers (2)

Mattie B
Mattie B

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

Mike Müller
Mike Müller

Reputation: 85492

You need to encode your string. Try this:

f.write(u'Río Negro'.encode('utf-8'))

Upvotes: 4

Related Questions