Python - 将表情符号字符写入日志文件

3

我在将表情符号字符写入.log文件时遇到了困难。以下是我代码的相关片段:

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)

当 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>

我已经查看了一些解决方案,但都没有成功。这个错误是否与我的日志文件编码有关?如果是,如何更改编码以允许utf-8字符?
一个可行但不理想的解决方案是检测字符串中是否存在这些字符,以便我可以选择不将内容写入日志。

1
你可以参考这个答案 https://stackoverflow.com/a/32233385/4662041,这可能会有所帮助。 我感觉问题在于你正在写入数据的文件的编码方式,如果是 utf-8,那么就不应该出现错误。 - Sheshnath
1个回答

1
这应该可以解决您的问题。来自:https://dev59.com/z6Hia4cB1Zd3GeqPUHp_#43813727
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接