UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 99: ordinal not in rang

F

Francach

Hi,

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?

Thanks for any tips,
Martin.
 
F

Fredrik Lundh

Francach said:
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>
 
D

Diez B. Roggisch

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?

You can. But if you write a unicode-object (wich is an abstract data
type with no byte representation), it has to be converted to a string -
which you have to do either explicit. Or if you don't do it - it ill be
done automatically, using the system default encoding. Which is ascii,
most of the time.

So do

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

Regards,

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top