Usage of Python serialization pickle/cPickle module, picklecpickle

Source: Internet
Author: User

Usage of Python serialization pickle/cPickle module, picklecpickle

The concept of Python serialization is very simple. The memory contains a data structure that you want to save, reuse, or send to others. What do you do? It depends on how you want to save, how to reuse, and who you want to send. Many games allow you to save the progress when you exit, and then go back to the last exit when you start again. (In fact, many non-game programs will 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, then load it from the hard disk when you restart.

The Python Standard Library provides the pickle and cPickle modules. CPickle is C-encoded and runs more efficiently than pickle, but the types defined in the cPickle module cannot be inherited (in most cases, we do not need to inherit from these types, cPickle is recommended ). The serialization/deserialization rules of cPickle and pickle are the same. You can use cPickle to deserialize an object by using pickle. At the same time, these two modules will become more "smart" when processing the self-reference type, and it will not recursively serialize the self-reference object without restrictions, for multiple references of the same object, it will be serialized only once.

The two main functions in the pickle module are dump () and load (). The dump () function accepts a data object and a file handle as parameters, and saves the data object to a specified file in a specific format. When we use the load () function to extract saved objects from a file, pickle knows how to restore these objects to their original format.

The dumps () function executes the same serialization as the dump () function. Instead of accepting stream objects and saving serialized data to disk files, this function simply returns serialized data.
The loads () function executes the same deserialization as the load () function. Instead of accepting a stream object and reading serialized data from a file, it accepts the str object that contains the serialized data and directly returns the object.

CPickle. dump (obj, file, protocol = 0)
Serialize the object and write the result data stream to the file object. The protocol parameter is a serialization mode. The default value is 0, indicating serialization in text format. The value of protocol can also be 1 or 2, indicating that the protocol is serialized in binary format.

CPickle. load (file)
Deserialization object. Parses the data in the file into a Python object.

The following is a simple example to demonstrate the use of the above two methods:

>>> import pickle,cPickle>>> info_dict = {'name':'yeho','age':100,'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 "<stdin>", line 1, in <module>NameError: name 'info_dict' is not defined>>> f = open('info.pkl','r+')>>> info2_dict = cPickle.load(f)>>> info2_dict{'Lang': 'Python', 'age': 100, 'name': 'yeho'}>>> info2_dict['age'] = 110>>> 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': 100, 'name': 'yeho'}>>> info2_dict = pickle.load(f)>>> info2_dict{'Lang': 'Python', 'age': 110, 'name': 'yeho'}>>> info3_dict = pickle.load(f)Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/pickle.py", line 1370, in load return Unpickler(file).load() File "/usr/lib64/python2.6/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib64/python2.6/pickle.py", line 880, in load_eof raise EOFErrorEOFError

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.