python 修改json文件(含中文)


1 先讀后寫(python3)

#!/usr/bin/python
import json
with open("replayScript.json", "r",encoding='utf-8') as jsonFile:
    data = json.load(jsonFile)

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

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

2 讀寫一起 移動文件位置指針(python3)

with open("replayScript.json", "r+",encoding='utf-8') as jsonFile:
    data = json.load(jsonFile)

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

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

3 數組類型讀寫

移除jsonarray最后一個元素

#!/usr/bin/python
import json

with open("./config/patchconfig/patch_log.json", 'r+',encoding='utf-8') as f:
    log = json.load(f)
    log.pop(len(log) - 1)
    f.seek(0)
    json.dump(log, f,ensure_ascii=False)
    f.truncate()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM