您的位置:首页 > 编程语言 > Python开发

python序列化存储模块:Pickle

2017-11-23 11:28 495 查看

python序列化存储模块:Pickle

  python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。

函数接口

  使用到主要接口有4个:dump, dumps, load, loads。其中dump和load用在序 列和序列对象,而dums与loads用在变量中,这个JSON的使用方法比较类似。

pickle.dump(obj, file, [,protocol])

  注解:将对象obj保存到文件file中去。

  protocol为序列化使用的协议版本,所支持的协议有5个,分别为: 0, 1, 2, 3 and 4。默认的3,这可以兼容Python2,如果是-1,则为最高的协议。关于则5中协议的定义官方文档如下:

  1. Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python.

Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.

  2. Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.

  3. Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.

  4.Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4.

  file:对象保存到的类文件对象。file必须有write()接口, file可以是一个以’w’方式打开的文件或者一个StringIO对象或者其他任何实现write()接口的对象。如果protocol>=1,文件对象需要是二进制模式打开的。

pickle.load(file)

  注解:从file中读取一个字符串,并将它重构为原来的python对象。file:类文件对象,有read()和readline()接口。

例子

dum

import pickle
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append([8,3])
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump((data1,selfref_list), output)
# Pickle the list using the highest protocol available.
# pickle.dump(selfref_list, output, -1)
output.close()


load

pkl_file = open('data.pkl', 'rb')
data1,data2 = pickle.load(pkl_file)
print(data1,data2)
pkl_file.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: