SoFunction
Updated on 2024-11-21

Sharing of cPickle usage examples in python

In python, you can generally use the pickle class for serializing python objects, and cPickle provides a faster and simpler interface, as the python documentation says: "cPickle -- A faster pickle".

cPickle can serialize any type of python object, such as a list, a dict, or even an object of a class. The so-called serialization, as I roughly understand it, is to be able to save the whole thing and be able to restore it in a completely reversible way. In cPickle, there are four main functions that can do this job, which are described below using examples.

1, dump: serialize python objects and save them to a local file.

Copy Code The code is as follows.

>>> import cPickle

>>> data = range(1000)

>>> (data,open("test\\","wb"))


dump function needs to specify two parameters, the first is the name of the python object to be serialized, the second is the local file, it should be noted that, here you need to use the open function to open a file, and specify the "write" operation.

2. load: load local file, restore python object

Copy Code The code is as follows.

>>> data = (open("test\\","rb"))

As with dump, you need to use the open function to open a local file and specify the "read" operation.

3. dumps: serialize a python object and save it to a string variable.

Copy Code The code is as follows.

>>> data_string = (data)

4. loads: loading python objects from string variables

Copy Code The code is as follows.

>>> data = (data_string)