为什么将json与discord.py一起使用时出错
嗨,我想在我的discord.py中添加一个货币系统。我正在使用json。我正在关注youtube上的教程。bot和我正在尝试以下代码:为什么将json与discord.py一起使用时出错,json,discord.py,Json,Discord.py,嗨,我想在我的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&qu
@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
如果您知道如何解决此问题,请提供帮助。您需要在写入模式下打开文件以写入文件(
json.dumps
写入文件),您可以通过执行open(“filename”,“w”)
打开文件,“w”
表示以写入模式打开。因为您将与open(“mainBank.json”,“r”)一起用作f:
。'r'
的意思是阅读。如果您只想附加新值,请使用'a'
,如果您想读写,请使用'r+
现在出现此错误:命令引发异常:JSONDecodeError:期望值:第1行第1列(字符0)
您的json文件是空的吗,意味着我希望它自动为使用该命令的用户创建一个空间。