我如何在json文件中存储各种用户的不一致.py命令?



这是我的代码,目前的问题是它只将最新的更改保存给我的用户。json文件。

@commands.command()
async def command(self, ctx):
userid = ctx.message.author.id
with open('users.json', "r", encoding="utf8") as f:
userdata = json.load(f)
try:
with open('users.json', "w", encoding="utf8") as f:
userdata[str(userid)]["coins"] = userdata[str(userid)]["coins"] + 1
json.dump(userdata, f, sort_keys=True, indent=4, ensure_ascii=False)
except:
with open('users.json', "w", encoding="utf8") as f:
userdata = {}
userdata[str(userid)] = {}
userdata[str(userid)]["coins"] = 0
json.dump(userdata, f, sort_keys=True, indent=4, ensure_ascii=False)

示例:我使用命令,这是存储在文件中的内容:

{
"idnumber": {
"coins": 0
}
}

但是如果其他人这样做了,我的变量硬币就会被他们的硬币所取代,只剩下:

{
"theiridnumber": {
"coins": 0
}
}

修复吗?

从您的代码中可以看出,您使用了try-除了查看是否不存在密钥等。这种用法是非常不必要的(也没有必要复杂),因为你可以很简单地使用各种字典方法get,setdefault等。
试试这个:

@commands.command()
async def command(self, ctx):
userid = str(ctx.message.author.id)
with open('users.json', "r", encoding="utf8") as f:
userdata = json.load(f)
userdata.setdefault(userid, {}) # if key exists do nothing else set as dictionary, also returns value for key
# dict.get(key, alternate) either gets the value for key or returns the alternate given
userdata[userid]["coins"] = userdata[userid].get("coins", -1) + 1
with open('users.json', "w", encoding="utf8") as f:
json.dump(userdata, f, sort_keys=True, indent=4, ensure_ascii=False)

最新更新