UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' inposition 99: ordinal not in range(128)

Fredrik Lundh fredrik at pythonware.com
Sun Nov 6 16:01:21 EST 2005


Francach wrote:

> I don't know what I'm doing wrong here.
> I''m using Python 2.4 and py2exe. I get he following error:
>
> Traceback (most recent call last):
>   File "notegui.pyc", line 34, in OnClose
>   File "brain.pyc", line 61, in setNote
>   File "points.pyc", line 151, in setNote
>   File "point.pyc", line 100, in writeNote
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in
> position 99: ordinal not in range(128)
>
> The piece of code involved is:
>
>       noteFileObj = open(noteFile, "wb")
>       noteFileObj.write(note)
>       noteFileObj.close()
>
> I would've thought that the 'b' option meant I can write any binary
> code I like to the file, but that's not so?

since you're getting a UnicodeEncodeError, the "note" object is probably
a Unicode string, not a "binary code".

to write Unicode strings to a file, you need to decide what encoding to
use, and encode the string on the way out.  e.g.

    nodeFileObj.write(note.encode("utf-8"))

to write it as a UTF-8 string.

</F>






More information about the Python-list mailing list