json - 为什么我在使用带有 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
如果您知道如何解决此问题,请提供帮助。
解决方案
您需要以写入模式打开文件才能写入它们(json.dumps
写入文件),您可以通过执行打开文件open("filename", "w")
,"w"
表示以写入模式打开。
推荐阅读
- docker - Docker 量角器运行以 E/launcher 结束 - 进程退出并出现错误代码 135
- javascript - 如何管理包含主题数据的组件的单元测试快照?
- python-3.x - 两个相似的脚本创建不同的列表
- egl - EGL:EGL_SURFACE_TYPE 并渲染到纹理
- node.js - 在选择提示中修改选择验证 - Bot Framework
- python - 将来自不同数据框的聚合添加为列
- java - 当我尝试从不同的类调用方法时,空对象引用
- python - 如何解释 python 字节数组中的空格
- c# - JSON.NET 反序列化:类型不匹配时忽略属性
- pandas - 条件 If 语句:如果行中的值以字符串中的字母开头……设置具有相应值的另一列