序列化:
#!usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "Samson"
import json,pickle
#json能用于其他语言中,只能序列化一些简单的数据类型,比如字典之类;而pickle只能用于python中,能序列化所有的数据类型
def sayhi(name):#程序运行结束时会释放掉该内存
print("name, ",name)
info = {
"name":"alex",
"age":22,
"func":sayhi#使用json序列化不行,而用pickle序列化是可以的
}
f = open("test.text","wb")
#print(json.dumps(info))
#f.write(json.dumps(info))#相当于json.dump(info,f)。**个人试了一下,若dump了很多次,则无法load()与loads(),最好用dumps
f.write(pickle.dumps(info))#相当于pickle.dump(info,f)
f.close()
反序列化:
#!usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "Samson"
import json,pickle
def sayhi(name):#必须有该函数名,否则不成功
print("name, ",name)
print("name2, ", name)
f = open("test.text","rb")
#data = json.loads(f.read())#相当于data2 = json.load(f)
data2 = pickle.loads(f.read())#相当于data2 = pickle.load(f)
f.close()
print(data2["func"]("Alex"))