为什么在discord.py中使用json时出现错误

时间:2020-09-08 14:28:38

标签: json discord.py

嗨,我想在我的discord.py中添加一个货币系统。我正在使用json。我正在关注YouTube上的教程。机器人,我正在尝试以下代码:

@client.command()
async def bal(ctx):
    user = ctx.author
    await open_account(ctx.author)
    users = await get_bank_data()
    wallet_amt = users[str(user.id)]["wallet"]
    bank_amt = users[str(user.id)]["bank"]

    em = discord.Embed(title=f"{ctx.author.name}'s balance")
    em.add_field(name = "Wallet", value = wallet_amt)
    em.add_field(name = "Bank", value = bank_amt)
    await ctx.send(embed=em)
    



async def open_account(user):
    users = await get_bank_data()

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0
    with open("mainBank.json", "r") as f:
        json.dump(users, f)
    return True



async def get_bank_data():
    with open("mainBank.json", "r") as f:
        users = json.load(f)
    return users

但是我遇到一个错误:

Ignoring exception in command bal:
Traceback (most recent call last):
  File "C:\Users\saheb\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:/Users/saheb/Documents/Discord Bot/DiscordBot.py", line 49, in bal
    await open_account(ctx.author)
  File "c:/Users/saheb/Documents/Discord Bot/DiscordBot.py", line 84, in open_account
    json.dump(users, f)
  File "C:\Users\saheb\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 180, in dump
    fp.write(chunk)
io.UnsupportedOperation: not writable

如果您知道如何解决此问题,请提供帮助。

2 个答案:

答案 0 :(得分:0)

您需要以写入模式打开文件以对其进行写入(json.dumps写入文件),可以通过执行open("filename", "w")打开文件,"w"表示要打开在写模式下。

答案 1 :(得分:-1)

因为您使用with open("mainBank.json", "r") as f:'r'表示已读。如果只想附加新值,请使用'a',如果要读取和写入,请使用'r+'