我需要在位于 json 檔案內的 dict 中編輯一個物件。但是每當我嘗試這樣做時,它都會洗掉整個 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
有什么方法可以運行它而不洗掉我的所有進度嗎?
uj5u.com熱心網友回復:
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
uj5u.com熱心網友回復:
您需要撰寫整個組態檔
你可以做這樣的事情......
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/333866.html
下一篇:php-將中文文本決議為json
