我需要在位于json文件内的字典中编辑对象。但是每当我尝试这样做时,它会删除整个json文件,只添加我编辑过的东西。
这是我的函数。
async def Con_Manage(keys):
with open('keys.json') as config_file:
config = json.load(config_file)[keys]
try:
Current_Con = config["curCons"] + 1
with open('keys.json', 'w') as config_file:
json.dump(Current_Con, config_file)
return True
except:
return False
这是我的json文件,在我运行它之前
{
"key1": {
"time": 1500,
"maxCons": 15,
"curCons": 2,
"coolDown": 2
}
}
这是它运行后的样子
3
有什么方法可以让我运行这个而不删除我所有的进度?
config["curCons"]
得到您的值,然后您增加它并分配给Current_Con
。相反,您需要将该值增加并设置为+1
。从那里你会想要保存整个json对象,你刚刚读进去,而不仅仅是更新的值。
async def Con_Manage(keys):
with open('keys.json') as config_file:
config = json.load(config_file)
config[keys]["curCons"] += 1 # mutates the value in place
with open('keys.json', 'w') as keys:
json.dump(config, keys) # saves the entire dict not just the value
您需要编写整个配置文件
你可以这样做…
with open('keys.json') as config_file:
config = json.load(config_file)
for key in keys:
try:
config[key]["curCons"] += 1
except KeyError:
pass
with open('keys.json', 'w') as config_file:
json.dump(config, config_file)