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

Discussion in 'Python' started by Francach, Nov 6, 2005.

  1. Francach

    Francach Guest

    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.
     
    Francach, Nov 6, 2005
    #1
    1. Advertisements

  2. 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>
     
    Fredrik Lundh, Nov 6, 2005
    #2
    1. Advertisements

  3. I would've thought that the 'b' option meant I can write any binary
    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
     
    Diez B. Roggisch, Nov 6, 2005
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.