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.

2
  • use .encode('utf-8') on the string? Commented Jun 4, 2013 at 16:56
  • You could search SO with your error code, there's 1,750+ results... Commented Jun 5, 2013 at 16:07

2 Answers 2

5

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')
Sign up to request clarification or add additional context in comments.

2 Comments

This. In Python 3, this functionality is provided by the 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).
4

You need to encode your string. Try this:

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

1 Comment

it assumes that f is a binary file ('wb' mode on Python 3).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.