我怎樣才能寫出更優化的這段代碼,而不是重復?所以,首先我要檢查是否有 .json 檔案,如果沒有,我會創建它。如果有,我首先打開它,用新資料更新它,然后再次寫入。
if not os.path.exists(json_path):
with open(json_path, "w") as json_file:
json.dump(my_dict, json_file)
else:
with open(json_path) as json_file:
data = json.load(json_file)
data.update(my_dict)
with open(json_path, 'w') as json__file:
json.dump(data, json__file)
uj5u.com熱心網友回復:
我認為您可以先反轉您的條件以讀取檔案。然后稍后寫入檔案,因為您總是最終寫入。
if os.path.exists(json_path):
with open(json_path) as json_file:
data = json.load(json_file)
data.update(my_dict)
my_dict = data
with open(json_path, "w") as json_file:
json.dump(my_dict, json_file)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433100.html
