Python serialization Pickle/cpickle Module usage Introduction

Source: Internet
Author: User
PythonThe concept of serialization is simple. There is a data structure in memory that you want to save, reuse, or send to others. What would you do? It depends on how you want to save it, how to reuse it, and who to send it to. Many games allow you to save your progress when you exit, and then go back to where you left off when you started again. (In fact, many non-gaming programs do the same) in this case, a data structure that captures the current progress needs to be saved to the hard disk when you exit, and then loaded from the hard disk when you reboot.

The Python standard library provides pickle and cpickle modules. Cpickle is encoded in C and is higher in efficiency than pickle , but the type defined in the Cpickle module cannot be inherited (most of the time, we do not need to inherit from these types, we recommend using Cpickle). The serialization/deserialization rules for cpickle and pickle are the same , use pickle to serialize an object that can be deserialized using Cpickle . At the same time, these two modules become more "smart" when dealing with self-referencing types, and it does not have unrestricted recursive serialization of self-referencing objects, which are serialized only once for multiple references to the same object.

The two main functions in the Pickle module are dump () and load (). The dump () function takes a data object and a file handle as a parameter, saving the data object in a specific format to a given file. When we use the load () function to remove a saved object from a file, pickle knows how to restore those objects to their original format.

The dumps () function performs the same serialization as the dump () function. Instead of accepting the stream object and saving the serialized data to a disk file, this function simply returns the serialized data.
The loads () function performs the same deserialization as the load () function. Instead of accepting a stream object and going to the file to read the serialized data, it takes the object directly back from the Str object that contains the serialized data.

Cpickle.dump (obj, file, protocol=0)
Serializes the object and writes the resulting data stream to the file object. The parameter protocol is a serialization mode with a default value of 0, which indicates serialization as text. The value of the protocol can also be 1 or 2, which is serialized as a binary representation.

Cpickle.load (file)
Deserializes the object. Resolves the data in a file to a Python object.

Here's a simple example to illustrate the use of the above two methods:

>>> Import pickle,cpickle>>> info_dict = {' name ': ' Yeho ', ' age ': $, ' Lang ': ' Python '}>>> f = Open (' Info.pkl ', ' WB ') >>> pickle.dump (info_dict,f) >>> f.close () >>> exit ()
# Cat Info.pkl (dp0s ' Lang ' P1s ' Python ' p2ss ' age ' p3i100ss ' name ' p4s ' Yeho ' p5s.
>>> import cpickle>>> info_dicttraceback (most recent call last): File "
  
    ", line 1, in 
   
     nameerror:name ' info_dict ' are not defined>>> f = open (' Info.pkl ', ' r+ ') >>& Gt Info2_dict = Cpickle.load (f) >>> info2_dict{' Lang ': ' Python ', ' age ': +, ' name ': ' Yeho '}>>> info2_ dict[' age ' = 110>>> cpickle.dump (info2_dict,f) >>> f.close () >>> exit () 
    
   /pre>
>>> import pickle>>> f = open (' Info.pkl ', ' r+ ') >>> info_dict = Pickle.load (f) >>> info_dict{' Lang ': ' Python ', ' age ': +, ' name ': ' Yeho '}>>> info2_dict = Pickle.load (f) >>> info2_dict{ ' Lang ': ' Python ', ' age ': +, ' name ': ' Yeho '}>>> info3_dict = Pickle.load (f) Traceback (most recent call last): Fi Le "
 
  
   
  ", line 1, in 
  
   
    
    File "/usr/lib64/python2.6/pickle.py", line 1370, in Load return Unpickler (f ile). Load () file "/usr/lib64/python2.6/pickle.py", line 858, and load Dispatch[key] (self) file "/usr/lib64/python2.6/ pickle.py ", line 880, in load_eof raise Eoferroreoferror
  
   
 
  
  • 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.