2012-12-19 348 views
22

我試圖更新現有的Json文件,但由於某種原因,所請求的值沒有被更改,但整個值(使用新值)正被追加到原始文件如何使用python更新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": "" 
} 

回答

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

這裏的問題是,您打開了一個文件並讀取其內容,因此光標位於文件的末尾。通過寫入相同的文件句柄,你基本上追加到文件。

最簡單的解決方法是在讀入文件後關閉文件,然後重新打開文件進行寫入。

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

感謝您解釋使用seek()和truncate()。然而,我會通過將'jsonFile.write(json.dumps(data))'改成'jsonFile.dump(data,f)'來改進這個答案。更pythonic。 – BoltzmannBrain