首页 > 解决方案 > 为什么我在使用带有 discord.py 的 json 时出现错误

问题描述

嗨,我正在尝试在我的 discord.py 中添加一个货币系统。我正在使用 json。我正在关注 youtube 上的教程。bot,我正在尝试这段代码:

@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

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

标签: jsondiscord.py

解决方案


您需要以写入模式打开文件才能写入它们(json.dumps写入文件),您可以通过执行打开文件open("filename", "w")"w"表示以写入模式打开。


推荐阅读