import pickle
#create a list, We are going to pickle this list and store it in disk
mylist = ['Apple', 'Banana', 'Orange', 'Pineapple']
#open a temp file in write mode
fh = open("C:\\Temp\\test.txt", 'w')
# dump the list l into file
pickle.dump(mylist, fh)
#close the file
fh.close()
#now if we open and see our file, we can see that python has saved this list
#but with some extra characters
""" Now, load the file back into the python data structure"""
#opne the file for reading
fh = open("C:\\Temp\\test.txt", 'r')
#create and empty list
mylist2 = []
#load the data from file to mylist2
mylist2 = pickle.load(fh)
print mylist2
""" We'll see that the out put is
['Apple', 'Banana', 'Orange', 'Pineapple']
In this way pickle can be used to save and load python data structure
to and from disk
Some of the uses of the pickling
1) saving a program's state data to disk so that it can carry on where it left off when restarted (persistence)
2) sending python data over a TCP connection in a multi-core or distributed system (marshalling)
3) storing python objects in a database
4) converting an arbitrary python object to a string so that it can be used as a dictionary key (e.g. for caching & memoization).
"""
Back to Python Home Page
No comments:
Post a Comment