The
pickle module can serialize objects and save them to disk and read them when needed, and any object can perform serialization operations. In machine learning, we often need to store a well-trained model so that we can make decisions by simply putting the model alone, without having to retrain the model, which saves time.
Pickle Module Common functions
Dump (Obj,file,[,protocol]) |
Serializes an Obj object into a file that is already open |
Load (file) |
Serializing an object in file to read |
Dumps (Obj,[,protocol]) |
Serializes an Obj object into a string, rather than depositing it in a file |
Loads (String) |
Reads the Obj object before serialization from a string |
Example
#Coding=utf-8Importpickledatalist= [[1, 1,'Yes'], [1, 1,'Yes'], [1, 0,'No'], [0,1,'No'], [0,1,'No']] Datadict= {0: [1, 2, 3, 4], 1: ('a','b'), 2: {'C':'Yes','D':'No'}} with open ("Pickle_test.txt","WB"as Writefp:pickle.dump (DataList, WRITEFP) Pickle.dump (Datadict, WRITEFP) with open ("Pickle_test.txt","RB") as Readfp:data1=pickle.load (READFP) data2=pickle.load (READFP)Print(data1)Print(DATA2) p=Pickle.dumps (DataList)Print(Pickle.loads (P)) p=pickle.dumps (datadict)Print(Pickle.loads (P))
>>> [[1, 1, ' yes '], [1, 1, ' yes '], [1, 0, ' no '], [0, 1, ' no '], [0, 1, ' no ']
>>> {0: [1, 2, 3, 4], 1: (' A ', ' B '), 2: {' c ': ' Yes ', ' d ': ' No '}}
>>> [[1, 1, ' yes '], [1, 1, ' yes '], [1, 0, ' no '], [0, 1, ' no '], [0, 1, ' no ']
>>> {0: [1, 2, 3, 4], 1: (' A ', ' B '), 2: {' c ': ' Yes ', ' d ': ' No '}}
dump and load have another ability compared to dumps and loads: the dump () function can sequentially store several objects in the same file, and then call Load () to deserialize the objects in the same order
The pickle of Python