python修改json文件 - python按行读取json文件



如何使用python更新json文件 (2)

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

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

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

tmp = data["location"]
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)

    tmp = data["location"]
    data["location"] = "NewPath"

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

https://ffff65535.com

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

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()




json