Example of Python pickle module usage

  • 2020-05-09 18:48:00
  • OfStack

The pickle module of python implements basic data sequencing and deserialization. Through the serialization operation of pickle module, we can save the object information running in the program to a file for permanent storage. Through the deserialization operation of the pickle module, we were able to create objects from the file that the program saved once before.

Basic interface:


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

Note: save the object obj to the file file.

protocol is the version of the protocol used for serialization, 0: ASCII protocol. The serialized objects are represented by the printable ASCII code. 1: old-fashioned base 2 protocol; Version 2:2.3 introduces a new base 2 protocol that is more efficient than the previous one. Among them, protocol 0 and 1 are compatible with the old version of python. protocol defaults to 0.

file: class file object to which the object is saved. file must have an write() interface, and file can be either a file opened in 'w' or an StringIO object or any other object that implements the write() interface. If protocol > =1, the file object needs to be opened in base 2 mode.

pickle.load(file)
Comment: read a string from file and refactor it to the original python object.
file: class file object with read() and readline() interfaces.

A Simple Code


# use pickle The module saves the data object to a file   import pickle data1 = {'a': [1, 2.0, 3, 4+6j], 'b': ('string', u'Unicode string'), 'c': None} selfref_list = [1, 2, 3]
selfref_list.append(selfref_list) output = open('data.pkl', 'wb') # Pickle dictionary using protocol 0. pickle.dump(data1, output) # Pickle the list using the highest protocol available. pickle.dump(selfref_list, output, -1) output.close()

 


# use pickle The module is refactored from the file python object   import pprint, pickle pkl_file = open('data.pkl', 'rb') data1 = pickle.load(pkl_file)
pprint.pprint(data1) data2 = pickle.load(pkl_file)
pprint.pprint(data2) pkl_file.close()


Related articles: