Your shopping cart is empty!
Python provides a standard module called pickle using which you can store any Python object in a file and then get it back later. This is called storing the object persistently.
# Filename: pickling.py
# the name of the file where we will store the object
shoplistfile = 'shoplist.data'
# the list of things to buy
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f) # dump the object to a file
del shoplist # destroy the shoplist variable
# Read back from the storage
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f) # load the object from the file
$ python pickling.py
['apple', 'mango', 'carrot']
How It Works:
To store an object in a file, we have to first open the file in 'w'rite 'b'inary mode and then call the dump function of the pickle module. This process is called pickling.
Next, we retrieve the object using the load function of the pickle module which returns the object. This process is called unpickling.