使用表情符号 Discord.py 写入文件 message.content 时出现问题
Problem with writing to a file message.content with emojis Discord.py
这是我在尝试写下包含表情符号的 post 的 message.content 时遇到的错误。我怎样才能避免这种情况?
discord.ext.commands.errors.CommandInvokeError: 命令引发异常: UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f609' in position
81:字符映射到
提前致谢。
这是我正在使用的代码:
async def posts(ctx):
f = open("file.txt", "w")
for channel in ctx.guild.text_channels:
f.write(message.content + "\n")
f.close()
问题是您没有使用 utf-8 编码。 open() 函数使用的标准编码不支持表情符号。因此错误。
要解决此问题,您需要将 encoding="utf-8"
添加到您的代码中:
async def posts(ctx):
f = open("file.txt", "w", encoding="utf-8")
for channel in ctx.guild.text_channels:
f.write(message.content + "\n")
f.close()
这是我在尝试写下包含表情符号的 post 的 message.content 时遇到的错误。我怎样才能避免这种情况?
discord.ext.commands.errors.CommandInvokeError: 命令引发异常: UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f609' in position 81:字符映射到
提前致谢。
这是我正在使用的代码:
async def posts(ctx):
f = open("file.txt", "w")
for channel in ctx.guild.text_channels:
f.write(message.content + "\n")
f.close()
问题是您没有使用 utf-8 编码。 open() 函数使用的标准编码不支持表情符号。因此错误。
要解决此问题,您需要将 encoding="utf-8"
添加到您的代码中:
async def posts(ctx):
f = open("file.txt", "w", encoding="utf-8")
for channel in ctx.guild.text_channels:
f.write(message.content + "\n")
f.close()