The pickle of Python

Source: Internet
Author: User
Tags serialization

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.