Home  >  Article  >  Backend Development  >  Python data persistent storage: basic use of pickle module

Python data persistent storage: basic use of pickle module

高洛峰
高洛峰Original
2016-12-16 11:38:131512browse

Python’s pickle module implements basic data sequence and deserialization. Through the serialization operation of the pickle module, we can save the object information running in the program to a file and store it permanently; through the deserialization operation of the pickle module, we can create the object saved by the last program from the file.

 Basic interface:

 pickle.dump(obj, file, [,protocol])
 Note: Save the object obj to the file file.
  Protocol is the protocol version used for serialization, 0: ASCII protocol, the serialized object is represented by printable ASCII code; 1: Old-fashioned binary protocol; 2: The new binary protocol introduced in version 2.3, which is more efficient than the previous one . Among them, protocols 0 and 1 are compatible with older versions of python. The default value of protocol is 0.
   File: File-like object to which the object is saved. File must have a write() interface. File can be a file opened in 'w' mode or a StringIO object or any other object that implements the write() interface. If protocol>=1, the file object needs to be opened in binary mode.

 pickle.load(file)
 Note: Read a string from file and reconstruct it into the original python object.
  File: File-like object with read() and readline() interfaces.

 A Simple Code

#使用pickle模块将数据对象保存到文件

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()
#使用pickle模块从文件中重构python对象

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()


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn