pickle序列化
# 想要将函数的复杂结构序列化,就要用pickle
# 如果在另一个程序中提取数据,那么需要再定义相同的函数def sayhi(name)
# 而函数的内容可以不同
1 import pickle 2 3 4 def sayhi(name): 5 print('hello,', name) 6 return name 7 8 9 info = dict(name='Flagon', age=33, func=sayhi) 10 # info里面的sayhi此处是func的值,所以不能加括号,加括号就是运行了 11 f_in = open('testpickle.txt', 'wb') 12 # pickle处理的型式为字节,所以用'wb' 13 data_in = pickle.dumps(info) 14 f_in.write(data_in) 15 f_in.close() 16 print('输入的内容:', data_in) 17 18 # 下面是反序列化 19 f_out = open('testpickle.txt', 'rb') 20 data_out = pickle.loads(f_out.read()) 21 # 读取时恢复成字典了 22 f_out.close() 23 print('Output age:', data_out['age']) 24 print('Output func:', data_out['func']('Danix'))