python之路-14.Json & pickle 数据序列化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之路-14.Json & pickle 数据序列化相关的知识,希望对你有一定的参考价值。
14.1序列化
示例1:
#!Author:lanhan
#把字典的内存数据类型通过字符串存到硬盘上(json.dumps),仅处理字符串、列表、字典等
import json
info = {
‘name‘:‘lanhan‘,
‘age‘:22
}
f = open("test.txt","w")
print(json.dumps(info))
f.write(json.dumps(info))
f.close()
示例2: pickle可处理复杂的,如函数等
import pickle
def sayhi(name):
print("hello",name)
info = {
‘name‘:‘lanhan‘,
‘age‘:22,
‘func‘:sayhi
}
f = open("test.txt","wb")
f.write(pickle.dumps(info))
示例3:
import json
def sayhi(name):
print("hello",name)
info = {
‘name‘:‘lanhan‘,
‘age‘:22
}
f = open("test.txt","w")
f.write(json.dumps(info))
info[‘age‘] = 21
f.write(json.dumps(info))
f.close()
14.2反序列化
示例1:
#!Author:lanhan
#把硬盘的数据类型恢复到内存中(json.loads),仅处理字符串、列表、字典等
import json
f = open("test.txt","r")
data = json.loads(f.read())
f.close()
print(data["age"])
示例2:pickle可处理复杂的,如函数等
##pickle
import pickle
def sayhi(name):
print("hello",name)
print("hello2",name)
f = open("test.txt","rb")
data = pickle.load(f) ###====#data = pickle.loads(f.read())
print(data["func"]("lanhan"))
示例3:
#!Author:lanhan
#c错误的,说明有多个状态能够多次dump,不能多次loads,也就是说有多个状态时就dump多个文件,dump一次,就load一次
import json
f = open("test.txt","r")
for line in f:
print(json.loads(line))
print(data)
以上是关于python之路-14.Json & pickle 数据序列化的主要内容,如果未能解决你的问题,请参考以下文章