Article directory
This
pickle
module implements the binary protocol for serializing and deserializing Python object structures.
-
Serialization: The process of converting an object into a sequence of bytes is called serialization of an object. Object information can be stored permanently
-
Deserialization: The process of restoring a sequence of bytes into an object is called object deserialization. Create the last program saved object
Serialization:
pickle.dump(obj, file,protocol)
Note: Save the object obj to the file file.
- file must have the write() interface, file can be a file opened with 'w' or a StringIO object or any other object that implements the write() interface.
- protocol is the protocol version used for serialization,
- 0: ASCII protocol, the serialized object is represented by printable ASCII code;
- 1: old-fashioned binary protocol;
- 2: The new binary protocol introduced in version 2.3 is more efficient than the previous one.
- The default value of protocol is 0.
import pickle
#使用pickle模块将数据对象保存到文件
data1 = {
'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list[:])
output = open('data.txt', 'wb')
# pickle字典使用协议0。
pickle.dump(data1, output)
# 使用可用的最高协议Pickle列表。
pickle.dump(selfref_list, output, -1)
output.close()
Deserialize:
pickle.load(file)
#使用pickle模块从文件中重构python对象
pkl_file = open('data.txt', 'rb')
data1 = pickle.load(pkl_file)
print(data1)
data2 = pickle.load(pkl_file)
print(data2)
pkl_file.close()
{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
[1, 2, 3, [1, 2, 3]]
When is serialization required?
- When you want to save the in-memory object state to a file or database;
- When you want to use sockets to transfer objects over the network;
- When you want to transfer objects via RMI;
- (The most commonly used may be stored in the database)