Python serialization Pickle/cpickle Module use introduction _python

Source: Internet
Author: User
Tags serialization

The concept of Python serialization is simple. There is a data structure in memory that you want to save, reuse, or send to others. What are you going to do? It depends on how you want to save, how to reuse, and who to send 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 your hard disk when you exit, and then load from the hard drive 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 types defined in Cpickle modules cannot be inherited (in fact, most of the time, we don't need to inherit from these types, we recommend using Cpickle). The serialization/deserialization rules for cpickle and pickle are the same to serialize an object using pickle, you can deserialize it using Cpickle . At the same time, these two modules become more "intelligent" when dealing with the self reference type, which does not have a recursive serialization of the self referencing object without restriction, and it is 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 parameters and saves the data object in a specific format to the given file. When we use the load () function to remove the saved object from the file, Pickle knows how to restore the 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 reading the serialized data, it accepts the Str object that contains the serialized data and returns the object directly.

Cpickle.dump (obj, file, protocol=0)
Serializes the object and writes the resulting data stream to the file object. 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 indicates serialization in binary form.

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

The following is 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
(dp0
s ' Lang '
p1
s ' Python '
p2
ss ' age '
P3
I100
SS ' name ')
P4
S ' Yeho '
P5
s.
 >>> import cpickle >>> info_dict traceback (most recent call last): File "<s Tdin> ", line 1, in <module> nameerror:name ' info_dict ' are not defined >>> f = open (' Info.pkl ', ' r+ ')  ;>> info2_dict = Cpickle.load (f) >>> info2_dict {' Lang ': ' Python ', ' age ': +, ' name ': ' Yeho '} >>> Info2_dict[' age '] = >>> cpickle.dump (info2_dict,f) >>> f.close () >>> exit () 
 >>> import pickle >>> f = open (' Info.pkl ', ' r+ ') >>> info_dict = Pickle . Load (f) >>> info_dict {' Lang ': ' Python ', ' age ': +, ' name ': ' Yeho '} >>> info2_dict = Pickle.load (f) &G t;>> info2_dict {' Lang ': ' Python ', ' age ': +, ' name ': ' Yeho '} >>> info3_dict = Pickle.load (f) traceback (M  OST recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/pickle.py", line 1370, In the Load return Unpickler (file). Load () file "/usr/lib64/python2.6/pickle.py", line 858, in load Dispatch[key] (self) Fi Le "/usr/lib64/python2.6/pickle.py", line 880, in load_eof raise Eoferror eoferror 
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.