22
我試圖更新現有的Json文件,但由於某種原因,所請求的值沒有被更改,但整個值(使用新值)正被追加到原始文件如何使用python更新json文件
jsonFile = open("replayScript.json", "r+")
data = json.load(jsonFile)
tmp = data["location"]
data["location"] = "NewPath"
jsonFile.write(json.dumps(data))
,其結果是: 要求:
{
"location": "NewPath",
"Id": "0",
"resultDir": "",
"resultFile": "",
"mode": "replay",
"className": "",
"method": "METHOD"
}
實際:
{
"location": "/home/karim/storm/project/storm/devqa/default.xml",
"Id": "0",
"resultDir": "",
"resultFile": "",
"mode": "replay",
"className": "",
"method": "METHOD"
}
{
"resultDir": "",
"location": "pathaaaaaaaaaaaaaaaaaaaaaaaaa",
"method": "METHOD",
"className": "",
"mode": "replay",
"Id": "0",
"resultFile": ""
}
感謝您解釋使用seek()和truncate()。然而,我會通過將'jsonFile.write(json.dumps(data))'改成'jsonFile.dump(data,f)'來改進這個答案。更pythonic。 – BoltzmannBrain