|
This document describes both Pickle and cPickle modules. Pickle allows you to subclass Pickler() and Unpickler() classes, cPickle does not but is much faster (up to 1000x).
dump(obj, file[, protocol]) and load(file)
# example from Python LibRef
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()
# READ OUR PICKLE
import pprint
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
pkl_file.close()
dumps(obj, [, protocol]) and loads(string) - Return the pickled representation of the object as a string, instead of writing it to a file, load object from a string.
# example from Python LibRef
obj = {'a':1,'b':2,'c':3}
from pickle import *
dumps(obj)
# "(dp0\nS'a'\np1\nI1\nsS'c'\np2\nI3\nsS'b'\np3\nI2\ns."