我目前正在使用discord.py机器人,希望在我的代码中更频繁地使用生成器。 但是,当我尝试使用输出生成器初始化对象方法时遇到错误。 这是我尝试做的事情:
def get_language_config(member: Member):
[role] = [role.name for role in member.roles if role.name in LANGS]
return LANGS_TO_CONFIG[role]
@client.command(name="ip")
async def ip_command(ctx):
sender = ctx.author
translation = get_language_config(sender)
data = Data(translation).read("langs")["IP_COMMAND"] # Here is the line that seems raise a problem.
embed = BaseEmbed(title=data["title"], description=data["description"])
embed.add_field(name=data["field_1"][0], value=data["field_1"][1])
await ctx.send(embed=embed, file=BaseEmbed.BASIC_FILE)
这是Data()对象类:
import json
class Data:
def __init__(self, data):
self.data = data
def update(self, key, value):
with open("data/config.json", "r", encoding="utf-8") as file:
json_data = json.load(file)
json_data[self.data][key] = value
with open("data/config.json", "w") as file:
json.dump(json_data, file, indent=2)
def read(self, file: str):
with open("data/%s.json" % file, "r+", encoding="utf-8") as json_file:
data = json.load(json_file)
return data[self.data]
输出错误:
ValueError: I/O operation on closed file
P.S .:很抱歉我的母语(我是法语),这是我第一次在网站上发布任何内容。
答案 0 :(得分:0)
您正在尝试读取已关闭的文件, 尝试使用以下方法打开它:
with open("YOUR_FILE", "r") as file:
data = Data(translation).read("file")["IP_COMMAND"]