python 修改json文件(含中文)

时间:2020-04-15 11:28:17   收藏:0   阅读:180

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

 

原文:https://www.cnblogs.com/wolbo/p/12703318.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!