Serializing Objects

Serializing an object is the process of converting the object to a stream of bytes that can be saved to a file for later retrieval. In Python, object serialization is called pickling.

In [2]:
import pickle # the Python standard library
In [ ]:
phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333','Thubsin':'123-888-3478'}
In [ ]:
# open a file for binary writing
outputfile = open('phonebook.dat','wb')

# dump the object into the file
pickle.dump(phonebook,outputfile)

# close the file
outputfile.close()
In [3]:
# retrieving the phonebook
inputfile = open('phonebook.dat','rb')
pb = pickle.load(inputfile)
inputfile.close()
In [4]:
pb
Out[4]:
{'Ekasit': '089-333-3333', 'Kanrop': '555-555-8888', 'Thubsin': '123-888-3478'}
In [ ]: