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()してカーソルをファイルの先頭に戻し、書き込みを開始して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()
于 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 に答える