『Python开发技巧』使用python处理json文件

json格式对应python里面的字典,可以通过json模块很方便保存处理,下面的代码用来抛砖引玉。。

保存json文件

def save_js(jsf,path):
    with open(path,"w",encoding="utf-8") as f:
        jsd = json.dumps(jsf)
        f.write(jsd)

读取json文件

def load_js(path):
    with open(path,"r") as f:
        jsd = f.read()
        jsf = json.loads(jsd)
    return jsf

使用示例

import json

def save_js(jsf,path):
    with open(path,"w",encoding="utf-8") as f:
        jsd = json.dumps(jsf)
        f.write(jsd)

def load_js(path):
    with open(path,"r") as f:
        jsd = f.read()
        jsf = json.loads(jsd)
    return jsf


test_dic = {"a":1,"b":2}

save_js(test_dic,"test.json")

read_dic = load_js("test.json")

print(test_dic,read_dic)

 

你可能感兴趣的:(Python开发技巧)