简体   繁体   中英

Python - Writing Emoji characters to a log file

I am having difficulty writing emoji characters to a .log file. Here is the relevant snipet of my code:

with open("testLog.log", "a") as myfile:
    print (message.content)                  #print to console - for debugging only
    print (message.content.encode('utf-8'))  #print to console - for debugging only
    myfile.write(message.content)

This is what is outputted into my console when message.content = 'hello there! 👍'

hello there! 👍                              
b'hello there! \xf0\x9f\x91\x8d'
Ignoring exception in on_message
Traceback (most recent call last):
    File "C:\path\to\file\file.py", line 29, in on_message
    myfile.write(message.content)
    File "C:\Python\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
    UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f44d' in position 13: character maps to <undefined>

I have looked around and tried some solutions, but to no avail. Is this error due to how my log file is encoded? If so, how can I change the encoding to allow utf-8 characters?

An allowable but not preferable solution would be a way to detect if these characters exist in the string so that I can instead not write the content to the log.

This should fix your issue. From: https://stackoverflow.com/a/43813727/6579239

with open("testLog.log", "a") as myfile:
    print (message.content)                  #print to console - for debugging only
    print (message.content.encode('ascii', 'ignore').decode('ascii'))  #print to console - for debugging only
    myfile.write(message.content)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM