You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Discord机器人报I/O operation on closed file错误如何解决

报错原因

Python 中with关键字用于文件操作时,会在缩进代码块执行结束后自动关闭文件句柄。你在全局作用域通过with open('data.json', 'r+') as data_file加载完JSON数据后,data_file句柄就已经被自动释放关闭,后续on_message事件触发时调用data_file.seek(0)操作已经关闭的文件,就触发了对应的报错。

修复方案

把data.json的写入逻辑移到!gcsetup指令内部,每次修改数据后重新打开文件写入即可,修改后完整代码如下:

import discord
import json

with open('config.json') as config_file:
    config = json.load(config_file)

# 仅读取初始data数据,不保留全局文件句柄
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)
        # 指令触发时单独打开文件写入
        with open('data.json', 'w') as data_file:
            json.dump(data, data_file)

client.run(config["token"])
可选优化点
  • 如果担心高频率触发指令导致文件写入冲突,可以给写入操作加异步锁
  • 如果data.json数据量很大,可以考虑定期批量写入,而不是每次触发指令都执行IO操作

内容的提问来源于stack exchange,提问作者Levente

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:45:03