Examples of cPickle usage in python

  • 2020-04-02 13:20:17
  • OfStack

In python, pickle classes are generally used for serializing python objects, and cPickle provides A faster and simpler interface, as the python documentation says: "cPickle -- A faster pickle."

CPickle can serialize python objects of any type, such as list, dict, or even objects of a class. What I mean by serialization is that it can be completely saved and reversibly recovered. In cPickle, there are four main functions that can do this, described in the following examples.

1, dump: serializes a python object and saves it to a local file.


>>> import cPickle
>>> data = range(1000)
>>> cPickle.dump(data,open("test\data.pkl","wb")) 

The dump function needs to specify two parameters, the first being the name of the python object to be serialized and the second being the local file. It is important to note that here you need to open a file using the open function and specify a write operation.

2. Load: load the local file and restore the python object


>>> data = cPickle.load(open("test\data.pkl","rb"))

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

3. Dumps: serializes the python object into a string variable.


>>> data_string = cPickle.dumps(data)

Load a python object from a string variable


>>> data = cPickle.loads(data_string)


Related articles: