source code: Lib/pickle.py
pickle模块实质上是一个实现python对象结构序列化的二进制协议。可以“序列化”,当然也可以“反序列化“。
python中也有一些其它的模块实现类似的功能,但一般情况下序列化使用pickle:
主要用于支持.pyc文件。考虑到扩展性以及功能性,一般情况下序列化使用Pickle。
json是一种文本序列化格式,是人类可读的,而Pickle不是。
关键是json支持的Python对象类型仅限于内置类型。
pickle使用的数据格式是python特定的。好处是不与其它协议冲突,坏处是其它协议不支持pickle格式。
默认情况下,pickle数据数据格式使用较高压缩率的二进制格式,当然,可以指定压缩率。
有5种协议用于序列化,越新的协议版本号越大,同样,需要新版的python。支持:
最原始的“人类可读”版协议,与早期的python版本兼容。
旧的二进制格式,与早期的Python兼容。
序列化使用dumps(),反序列化使用loads()。如果需要进行更多的细节控制,可以使用Pickler和Unpickler对象。
模块常量:
整数,支持协议的最高版本。
整数,默认协议版本。目前默认是3.
方法:
将对象序列化并写入文件句柄。
protocol,一个可选参数,整数,使用指定版本协议。
file参数必需有支持字节写入的write()方法,
fix_imports主要用于与python2的兼容,一般不用设置。
将对象序列化并返回一个二进制对象。
从指定文件对象中读取序列化对象。
协议版本自动查看。
对应于dumps。
import pickle
from json import load
a = pickle.HIGHEST_PROTOCOL
print(a)
a = pickle.DEFAULT_PROTOCOL
print(a)
with open(‘nums.txt‘, ‘r‘, encoding=‘utf-8‘) as fi:
lisa = load(fi)
print(len(lisa))
file_a = ‘pickle_a.txt‘
with open(file_a, ‘wb+‘) as fi:
pass
pickle.dump(lisa,fi)
file_a = ‘pickle_a.txt‘
with open(file_a, ‘rb+‘) as fi:
pass
pickle.dump(lisa,fi)
pickle模块定义了三种异常:
pickle模块异常类的基类,继承于Exception.
This takes a binary file for writing a pickle data stream.
methods:
dump(obj) 将obj pickle化并写入file
This takes a binary file for reading a pickle data stream.
load() 从文件句柄中读取pikled对象并反序列化。返回反序列化后的对象。
下面这些对象是可以序列化和反序列化的。
None, True, and False
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, not lambda)
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 of calling __getstate__() is picklable (see section Pickling Class Instances for details).
笔记-python-standard library-12.1 pickle
原文:https://www.cnblogs.com/wodeboke-y/p/9784018.html