96

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

2 回答 2

161

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

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

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()将光标移回文件开头然后开始写入,然后使用 atruncate()来处理新数据小于前一个的情况。

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

    data["location"] = "NewPath"

    jsonFile.seek(0)  # rewind
    json.dump(data, jsonFile)
    jsonFile.truncate()
于 2012-12-19T10:04:40.543 回答
51
def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()
于 2012-12-19T10:04:17.070 回答