Python module (a): Pickle

1.pickle role

pickle module provides a simple persistence function. Python objects can be in the form of a file stored on disk. pickle protocol module implements the basic binary data sequence and deserialization Python object structures.

Tips:

Python, the two modules have a similar function: pickle and json.

  • json: for inter-string data type conversion and Python.
    • json provides four functions: dumps / loads / jump / load
  • Between data types for Python pickle specific type of conversion and Python
    • pickle provides four functions: dumps / loads / dump / load

2.pickle use

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

  • obj: Required parameter representing the object to be wrapped Python
  • file: Required parameter that indicates the object obj file to be filled. Binary file must be opened in write mode, namely "wb".
  • protocol: optional parameters. pickle protocol represents a protocol used to inform, to support the agreement 0,1,2,3, the default protocol is to add a protocol 3.
    dump is converted to a string Python be identified by a special form, and write files

import pickle
folder = {'name':Ricardo, 'age':21, 'address':Zhejiang, 'hobby':code}
pickle_file = open('folder.pkl', 'wb')
pickle.dump(folder, pickle_file)

Output: pkl will automatically generate a file in the current py file.

2.pickle.load(file, *, fix_import=True, encoding=“ASCII”, errors=“strict”)

  • file: Required parameter must be opened in binary read mode, i.e., 'rb'.
  • Other parameters are optional parameters, not very important, not repeat them here.

load the data file is read from the data, and converts the data structure of the Python

import pickle
pickle_file = open('folder.pkl', 'rb')
my_file = pickle.load(pickle_file)
print(my_file)

Output:


3.pickle.dumps(obj)

  • obj: Required parameter representing the object to be packaged Python.
    Return the package objects in the form of bytes of the object, need to write the file (i.e., does not need to open ()).
    The only character data into knowledge through a special form python
import pickle
data = ['aa', 'bb', 'cc']
p_byte = pickle.dumps(data)
print(p_byte)

Output:Here Insert Picture Description


4.pickle.loads(obj)

  • obj: Required parameter, obj byte object.
    loads the object to read a byte from the byte encapsulated object.
    Converting the data into data of python pickle.
import pickle
data = ['aa', 'bb', 'cc']
p_byte = pickle.dumps(data)
file = pickle.loads(p_byte)
print(file)

Output:
Here Insert Picture Description
Reference:
https://www.cnblogs.com/lincappu/p/8296078.html

Released two original articles · won praise 0 · Views 60

Guess you like

Origin blog.csdn.net/Ricardo_ChenM/article/details/104594765