「Python」 pickle:对象序列化
对任意的 python 对象进行序列化(将对象转换成二进制流)和反序列化;
Python 3.7.2 官方文档:https://docs.python.org/3/library/pickle.html
API
一、 Hello World
- 序列化之后的数据可以写到文件、套接字、管道或其他位置;
- 反序列化时要保证该对象的定义在当前进程中可见,否则序列化会报错;
- 并不是所有对象都能够序列化;
套接字、文件句柄、数据库链接以及其他运行时状态,这些依赖于操作系统或其他进程的对象,无法保存;
循环引用
附录
A API
B 示例
1. hellow world
import pickle
import pprint
data = [{'a':'A', 'b':2, 'c':3.0}]
print('BEFOR:', end=' ')
pprint.pprint(data)
data_str = pickle.dumps(data) # serialization
print('PICKLE:{!r}'.format(data_str))
data2 = pickle.loads(data_str) # deserialization
print('AFTER:', end=' ')
pprint.pprint(data2)
with open("file.pkl", 'wb') as out_s: # write
pickle.dump(data, out_s)
with open("file.pkl", 'rb') as in_s: # load
data3 = pickle.load(in_s)
print('LOAD:', end=' ')
pprint.pprint(data3)
C 推荐资料
- Antoine Pitrou (solipsis at pitrou.net). 第四版 pickle 协议[EB/OL]. https://www.python.org/dev/peps/pep-3154/. 2011-08-11/2019-01-28.
- Max Lawnboy. Don’t Trust a Pickle[EB/OL]. https://hackernoon.com/dont-trust-a-pickle-a77cb4c9e0e. 2018-01-25/2019-01-28.
- pickle an interesting stack language[EB/OL]. http://peadrop.com/blog/2007/06/18/pickle-an-interesting-stack-language/. 2007-01-18/2019-01-28.
D 参考资料
- Doug Hellmann 著, 苏金国, et al 译. Python3 标准库[M]. 北京:机械工业出版社, 2018.
Comments