Python basic usage of pickle

Python pickle

import pickle

#dumps(object) :Object serialization
#print listb

#loads(string) :The object is restored, and the object type is restored to the original format.
#print listc

#dump(object,file) :To store objects in a file.

#load(object,file) :Data recovery stored in file
print t

Python Pickle module to achieve the basic data sequences and anti serialization. Through the serialization of the pickle module operation we can program operation of the object information is saved to a file to, permanent storage; through the pickle module deserialization operation, we are able to create a program to save the object from a file.

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

  Note: the object file is saved to the file obj.
Using serialization protocol version of the protocol, protocol 0:ASCII, the serialized objects using printable ASCII code said; 1: new binary protocol old-fashioned binary protocol. Version 2:2.3 introduced, compared with the previous more efficient. The protocol 0 and 1 are compatible with older versions of python. The default value of protocol is 0.
File: the class file object that is saved to the object. File must have a write () interface, file can be a'w'to open the file or a StringIO object or any other object to achieve write () interface. If protocol>=1, the file object needs to be opened in binary mode.

Pickle.load (file)

    Note: reads a string from the file, and it is reconstructed to the original Python object.
File: class file object, there are read () and readLine () interface.

A Simple Code

#Save data objects to a file using the pickle module

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]

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)


#Using the pickle module to reconstruct the python object from the file

import pprint, pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)

data2 = pickle.load(pkl_file)


Pingbacks are closed.

Comments are closed.