Python basic usage of pickle

Python pickle

import pickle

#dumps(object) :Object serialization
lista=["john","levi","kate"]
listb=pickle.dumps(lista)
#print listb

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

#dump(object,file) :To store objects in a file.
group1=("cat","is","kkkk")
f1=file('1.pk1','wb')
pickle.dump(group1,f1,True)
f1.close()

#load(object,file) :Data recovery stored in file
f2=file('1.pk1','rb')
t=pickle.load(f2)
print t
f2.close()

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



#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)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()

Pingbacks are closed.

Comments are closed.