我的代碼有問題,我不知道如何解決。我發現了很多類似的問題,但沒有一個能解決我的問題。我使用 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.
uj5u.com熱心網友回復:
當您使用該with open()...陳述句打開檔案句柄時,您在 with 塊的末尾隱式關閉了句柄。因此,當您呼叫時,data_file.seek您正在嘗試對關閉的檔案執行 I/O 操作,如錯誤訊息所示。
最簡單的解決方案是在執行轉儲時重新打開檔案進行寫入。這也避免了尋找檔案開頭的需要,因為這將是您以寫入模式打開時的默認行為。
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)
雖然您也可以不使用 with 塊(因此永遠不要關閉檔案句柄),但最好不要為整個 Discord 服務器保留大量打開的檔案句柄
uj5u.com熱心網友回復:
data_file變數僅存在于with open('data.json', 'r ') as data_file:塊中,因此您不能在with.
試著寫
data_file = open('data.json', 'r ')
data = json.load(data_file)
代替
with open('data.json', 'r ') as data_file:
data = json.load(data_file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371295.html
上一篇:如何使用docker容器中的檔案
