gpt4 book ai didi

python - 如何用python更新json文件

转载 作者:IT老高 更新时间:2023-10-28 12:45:42 26 4
gpt4 key购买 nike

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

最佳答案

这里的问题是您打开了一个文件并读取了它的内容,因此光标位于文件的末尾。通过写入同一个文件句柄,您实际上是在追加文件。

最简单的解决方案是在读入文件后将其关闭,然后重新打开以进行写入。

with open("replayScript.json", "r") as jsonFile:
data = json.load(jsonFile)

data["location"] = "NewPath"

with open("replayScript.json", "w") as jsonFile:
json.dump(data, jsonFile)

或者,您可以使用 seek()将光标移回文件的开头然后开始写入,然后是 truncate()处理新数据小于之前的情况。

with open("replayScript.json", "r+") as jsonFile:
data = json.load(jsonFile)

data["location"] = "NewPath"

jsonFile.seek(0) # rewind
json.dump(data, jsonFile)
jsonFile.truncate()

关于python - 如何用python更新json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13949637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com