Detailed introduction to the use of Python3 pickle module

  • 2021-12-05 06:29:45
  • OfStack

pickle Module Features

1. It can only be used in python, and only supports the basic data types of python.

2. Can handle complex serialization syntax. (For example, custom class methods, game archiving, etc.)

3. When serializing, only the whole sequence object is serialized, not the memory address.

pickle: Used to convert the specific type of python and the data type of python. pickle provides four functions: dumps, dump, loads and load

What kind of data can pickle store?

All native types supported by python: Boolean, integer, floating-point, complex, string, byte, None.

Lists, tuples, dictionaries, and collections of any native type.

Functions, classes, instances of classes

Methods commonly used in pickle module

1. pickle.dump(obj, file, protocol=None,)

Required parameter obj indicates the object to be encapsulated

Required parameter file indicates the file object to be written by obj. file must be opened in binary writable mode, that is, "wb"

The optional parameter protocol indicates the protocol used by pickler. The supported protocols are 0, 1, 2 and 3, and the default protocol is Protocol 3 added to Python 3.

2. pickle.load(file,*,fix_imports=True, encoding="ASCII", errors="strict")

Required parameter file must be opened in binary readable mode, that is, "rb", and others are optional

3. pickle. dumps (obj): Returns an encapsulated object as a byte object without writing to a file 4. pickle. loads (bytes_object): Reads the encapsulated object from the byte object and returns

Three Exception Types of pickle Module

1. PickleError: Exception class that occurs during encapsulation and unencapsulation, inherited from Exception

2. PicklingError: Exception when an object is not encapsulated, inherited from PickleError

3. UnPicklingError: Exception occurred during unpacking object, inherited from PickleError

pickle code example

dumps Function

dumps converts data into strings only known by python in a special form


import pickle
data = ['aa', 'bb', 'cc']  
# dumps  Convert data into only one in a special form python String of language cognition 
p_str = pickle.dumps(data)
print(p_str)

Results:


b'\x80\x03]q\x00(X\x02\x00\x00\x00aaq\x01X\x02\x00\x00\x00bbq\x02X\x02\x00\x00\x00ccq\x03e.
loads Function

loads converts pickle data into python data structure


mes = pickle.loads(p_str)
print(mes)

Results:


['aa', 'bb', 'cc']

For more information on the python pickle module, see the links below


Related articles: