【发布时间】:2021-11-29 17:40:41
【问题描述】:
我的代码有问题,我不知道如何解决。我发现了很多类似的问题,但没有一个能解决我的问题。我使用 Visual Studio Code 作为代码编辑器。这是我的代码:
import discord
import json
with open('config.json') as config_file:
config = json.load(config_file)
with open('data.json', 'r+') as data_file:
data = json.load(data_file)
client = discord.Client()
@client.event
async def on_ready():
print("Logged in as " + str(client.user))
@client.event
async def on_message(msg):
if msg.author == client.user: return
if msg.content == '!gcsetup':
server_json_content = {}
server_json_content["channel"] = msg.channel.id
webhook = await msg.channel.create_webhook(name="name")
server_json_content["webhook"] = webhook.url
data.append(server_json_content)
data_file.seek(0)
json.dump(data, data_file)
client.run(config["token"])
我认为错误在这里:
if msg.content == '!gcsetup':
server_json_content = {}
server_json_content["channel"] = msg.channel.id
webhook = await msg.channel.create_webhook(name="name")
server_json_content["webhook"] = webhook.url
data.append(server_json_content)
data_file.seek(0)
json.dump(data, data_file)
根据报错错误信息:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "E:\Dev\main.py", line 26, in on_message
data_file.seek(0)
ValueError: I/O operation on closed file.
【问题讨论】:
-
data_file 变量在哪里定义。换句话说,你在哪里打开了一个文件并将其保存在 data_file 中?!
-
@Grasshopper with open('data.json', 'r+') as data_file
-
用你自己的话来说,
with open('data.json', 'r+') as data_file:是什么意思?您认为该区块的末尾会发生什么?您认为使用with语句而不是简单地正常调用open的目的是什么? -
除了其他人解释的问题的直接答案之外,全局变量通常不受欢迎。它们可能会导致像这样的错误。如果您使用本地
with块打开on_message()中的data.json文件,那么您将完全避免该问题。