Json与Pickle :功能主要用于文件数据序列化操作

   1:Json的存数据到文件:

import json
info = {
    "name":"hjc",
    "age":22
}
with open("a1.txt","w",encoding="utf-8") as f:
    f.write(json.dumps(info))

  2.Json的取数据

import json
with open("a1.txt","r",encoding="utf-8") as f:
    data = json.loads(f.readline())
    print(data["age"])

  3.Pickle的存数据

import pickle
 
def func():
    print("hello tomorrow!!!")
 
info = {
    "name" : "hjc",
    "age" : 24,
    "hobby" : func
}
with open("a1.txt","wb") as f:
    f.write(pickle.dumps(info))

  4.Pickle的取数据:

import pickle
 
def func():
    print("hello tomorrow!!!")
 
with open("a1.txt","rb") as f:
    data = pickle.loads(f.read())
data["hobby"]()

  *pickle 读写都是采用二进制,所以要使用'rb' & 'wb'

#文章引用KaShing大神

posted on 2017-10-10 17:37  缪阿布  阅读(137)  评论(0编辑  收藏  举报