一、pickle模块的作用
python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
好处:无版本兼容问题
tips:可以使用文本编辑器查看序列化的文本。我们也可以序列成二进制格式的数据,这样的结果体积会更小。
二、py3版本如何简单使用pickle
Note: python3中使用pickle写入或者读入的文件要以‘b‘的方式 、打开,否则出错TypeError: must be str, not bytes.
import pickle # An arbitrary collection of objects supported by pickle.#由pickle支持的任意对象集合。 data = { 'a': [1, 2.0, 3, 4+6j], 'b': ("character string", b"byte string"), 'c': set([None, True, False]) }
#比如这个data是一个内容为一个字典后缀为pickle的文件
#用二进制写文件的方式打开pickle对象 with open('data.pickle', 'wb') as f: # Pickle the 'data' dictionary using the highest protocol(协议) available.#使用可用的最高协议pickle字典data?? pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
The following example reads the resulting pickled data.
#接下来的例子读取已经被pickle的数据结果。
import pickle
with open('data.pickle', 'rb') as f:
# The protocol version used is detected automatically, so we do not
# have to specify it.#协议版本被自动探测到并且使用,所以我们不需要明确它是什么。
data = pickle.load(f)#使用pickle的load函数下载被打开被读取到的数据。
pickle支持的序列化类型
The following types can be pickled:
None
,True
, andFalse
- integers, floating point numbers, complex numbers
- strings, bytes, bytearrays
- tuples, lists, sets, and dictionaries containing only picklable objects
- functions defined at the top level of a module (using
def
, notlambda
) - built-in functions defined at the top level of a module
- classes that are defined at the top level of a module
- instances of such classes whose
__dict__
or the result ofcalling__getstate__()
is picklable (see section Pickling Class Instances fordetails).
1.一般的数据类型——整形,浮点型,复杂的数字类型。
2.字符串,字节,字节数组(不常见?)元组,列表,集合。
3.还有只含有可以被pikle对象的字典。
4.放在一个模型顶部的函数(采用def定义的而不是lambda)。
5.后面的标记为紫色部分好像都不常用,一般不会遇到这种冲突。
以上引自 http://blog.youkuaiyun.com/pipisorry/article/details/45315483,但已添加注释内容。