Python's pickle module implements basic data sequence and deserialization. Through the serialization of the Pickle module we are able to save the object information running in the program to a file, to store it permanently, and through the Pickle module's deserialization, we are able to create from the file the last object saved by the program.
The most commonly used functions in the Pickle module are: Dump, dumps, load, loads
(1) pickle.dump (obj, file, [, Protocol])
Function: Serializes the Obj object into a file that is already open.
Parameter explanation:
Obj: The obj object that you want to serialize.
File: filename, is a file object with Write permission, if protocol>=1, file needs to operate in binary (WB) Form.
Protocol: The protocol used by serialization. If the item is omitted, the default is 0. If negative or Highest_protocol, the highest protocol version is used.
(2) pickle.load (file)
Function: Serializes the object in file to read out.
Parameter explanation:
File: filename, is a file object with Read permission, if protocol>=1, file needs to operate in binary (RB) Form
(3) Pickle.dumps (obj[, Protocol])
Function: Serializes an Obj object into a string, rather than depositing it in a file.
Parameter explanation:
Obj: The obj object that you want to serialize.
Protocal: If the item is omitted, the default is 0. If negative or Highest_protocol, the highest protocol version is used.
(4) pickle.loads (string)
Function: Reads the Obj object before serialization from a string.
Parameter explanation:
String: File name.
"Note" Dump () has another capability compared to load () dumps () and loads (): the dump () function can sequentially store several objects into the same file, and then call Load () to deserialize the objects in the same order.
#!/usr/bin/env python#-*-coding:utf-8-*-#@Time: 2017/12/26 0026 15:18#@Author: Ming__author__='Ming'#application Examples of main functions of pickle moduleImportpickledatalist= [ ["Yang", 20,'6873264382'], ["Ming", 32,'7298349832'], ["Coke", 14,'2937972439'],]datadic= { "A": [1, 2, 3, 4, ], "B": ('Hello',' World',), "C": {'my':'Yes',' You':'No'}}#serializing data to a file using dump ()FO = open ('File.txt','WB') pickle.dump (DataList, FO,-1) pickle.dump (datadic, FO) fo.close ()#use Load () to serialize data from a fileFO = open ('File.txt','RB') Data1=pickle.load (FO)Print(data1) data2=pickle.load (FO)Print(DATA2) fo.close ()#examples of using dumps () and loads ()p =pickle.dumps (DataList)Print(Pickle.loads (P)) p=pickle.dumps (datadic)Print(Pickle.loads (P))
[['Yang', 20,'6873264382'], ['Ming', 32,'7298349832'], ['Coke', 14,'2937972439']]{'A': [1, 2, 3, 4],'C': {'my':'Yes',' You':'No'},'B': ('Hello',' World')}[['Yang', 20,'6873264382'], ['Ming', 32,'7298349832'], ['Coke', 14,'2937972439']]{'A': [1, 2, 3, 4],'C': {'my':'Yes',' You':'No'},'B': ('Hello',' World')}
Python Pickle Module