pickle module

  In machine learning, we often need to be trained model stored directly read out this model in decision making, without the need to re-train model, thus greatly saves time. Python pickle module provides a good solution to this problem, it can serialize an object and saved to disk and read it when needed, any object can perform a sequence of operations.

Pickle module is most commonly used functions:

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

        Function function: the obj object serialization stored in the file has been opened.

       Parameters explanation:

  • obj: obj want to serialize objects.
  • file: file name.
  • protocol: Protocol used in serialization. If this is omitted, the default is 0. If negative or HIGHEST_PROTOCOL, then use the highest protocol version.

(2)pickle.load(file)

        Function Function: the file of the read object serialization.

        Parameters explanation:

  • file: file name.

(3)pickle.dumps(obj[, protocol])

       Function function: obj will serialize objects into string form, rather than stored in the file.

       Parameters explanation:

  • obj: obj want to serialize objects.
  • protocal: If this is omitted, the default is 0. If negative or HIGHEST_PROTOCOL, then use the highest protocol version.

(4)pickle.loads(string)

       Function Function: reading out object obj from the front of the string serialization.

       Parameters explanation:

  • string: file name.

     [Note] dump () and load () compared dumps () and loads () there is another capability : dump () function can be several one after the sequence of stored objects to the same file, then calls load () in the same order to deserialize objects read out.

     [Code example]

      pickleExample.py

#coding: UTF - . 8   
__author__ =  ' MsLili '   
application #pickle main function module Example   
Import the pickle   
dataList =  [ [. 1,. 1, 'Yes' ] ,  
             [ . 1,. 1,' Yes' ] ,  
             [ . 1, 0, ' NO ' ] ,  
             [ 0,. 1,' NO ' ] ,  
             [ 0,. 1,' NO ' ] ]   
dataDic = { 0 : [ . 1, 2,. 3,. 4 ] ,  
             . 1 : ( ' A' , ' B ' ),  
             2 : { ' C ' : ' Yes ' , ' D ' : ' NO ' }}   
  
# use dump () to serialize the data file   
FW =  Open ( ' datafile.txt ' , ' WB ' )   
# The Pickle The Highest the using Protocol List Available.   
the pickle. the dump (dataList, FW, - . 1 )   
# Pickle Dictionary the using Protocol 0  .  
the pickle. the dump (dataDic, FW)   
FW. Close ()   
  
# using load () of the sequence from the document read out data   
fr =  Open ( ' datafile.txt ' , ' RB ' )   
DATAl = the pickle. Load (fr)  
 Print (DATAl)   
DATA2 = the pickle. Load (fr)  
 Print (DATA2)   
fr. Close ()   
  
# use dumps () and loads () example   
P = the pickle.dumps (dataList)  
 Print (The pickle.loads (P))   
P = pickle.dumps(dataDic)  
print( pickle.loads(p) )  

 

Guess you like

Origin www.cnblogs.com/chen8023miss/p/11498160.html