我正在尝试更新现有的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。