[Python] How to open a text file that has emojis in it?

Discussão em 'Python' iniciado por Stack, Abril 14, 2025.

  1. Stack

    Stack Membro Participativo

    I´m trying to do the simplest thing, open a file, read and close it in python. Simple. Well this is the code:

    name_file = open("Forever.txt", encoding='UTF-8')
    data = name_file.read()
    name_file.close()

    print (data)


    I know that this texts has emojis in it like hearts, etc. The thing is that this emojis are not in there unicode syntax like U+2600 , they are placed as little images. I think the following error is because of this little images:

    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
    UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f681' in
    position 2333: character maps to <undefined>


    I tried the following, without specifyng encoding:

    name_file = open("Forever.txt")


    And the error changed to this:

    UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 2303: character maps to <undefined>


    No idea why is this happening.

    Maybe one solution would be to save in a variable everything that is test and deleting the rest...mmm.

    Continue reading...

Compartilhe esta Página