|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
# 想要将函数的复杂结构序列化,就要用pickle
# 如果在另一个程序中提取数据,那么需要再定义相同的函数def sayhi(name)
# 而函数的内容可以不同
- import pickle
- def sayhi(name):
- print('hello,', name)
- return name
- info = dict(name='Flagon', age=33, func=sayhi)
- # info里面的sayhi此处是func的值,所以不能加括号,加括号就是运行了
- f_in = open('testpickle.txt', 'wb')
- # pickle处理的型式为字节,所以用'wb'
- data_in = pickle.dumps(info)
- f_in.write(data_in)
- f_in.close()
- print('输入的内容:', data_in)
- # 下面是反序列化
- f_out = open('testpickle.txt', 'rb')
- data_out = pickle.loads(f_out.read())
- # 读取时恢复成字典了
- f_out.close()
- print('Output age:', data_out['age'])
- print('Output func:', data_out['func']('Danix'))
复制代码 |
|