Python: pickle module learning

1. The role of pickle module

Persist objects such as dictionaries, lists, and strings, and store them on disk for future use

 

2. Pickle object serialization

The process by which the pickle module converts any python object into a system byte is called serializing the object

 

3. pickle和cpickle

The Python standard library provides pickle and cPickle modules. cPickle is coded in C, which is more efficient than pickle , but the types defined in the cPickle module cannot be inherited (in fact, most of the time, we do not need to inherit from these types, and cPickle is recommended ). The serialization/deserialization rules of cPickle and pickle are the same, use pickle to serialize an object, you can use cPickle to deserialize .

 

4. Commonly used functions in pickle

(1)pickle.dump(obj, file, [,protocol])

Function: Save the data "object" to be persisted to "file", using 3 protocols, index 0 is ASCII, 1 is old-style binary, 2 is new-style binary protocol, the difference is that 2 is more efficient ( 0 protocol is used by default)

 

(2)pickle.load(file)

Role: read strings from "files", deserialize them into python data objects

 

(3)pickle.dumps(obj[, protocol])

Role: serialize the obj object into a string form instead of storing it in a file

  • obj: the obj object you want to serialize
  • protocal: If this item is omitted, it defaults to 0. If negative or HIGHEST_PROTOCOL, use highest protocol version

(4)pickle.loads(string)

Role: read the obj object before serialization from the string

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324539169&siteId=291194637