What is Pickle in python ?
It is used for serializing and de-serializing a Python object structure.
Pickling: It is a process where a Python object hierarchy is converted into a byte stream and dumps it into a file by using dump function.This character stream contains all the information necessary to reconstruct the object in another python script.
Unpickling: It is the inverse of Pickling process where a byte stream is converted into an object hierarchy.While the process of retrieving original Python objects from the stored string representation is called unpickling.we use load function to do this.
First of all you have to import pickle module through this command:
import pickle
pickle has two main methods. The first one is dump, which dumps an object to a file object and the second one is load, which loads an object from a file object.
Pickling:
import pickle
a=[1, 2, 3, 4, 5, 6, 7]
# open the file for writing
pic_out=open("mypicklefile","wb")
#write object to file mypicklefile
pickle.dump(a,pic_out)
pic_out.close()
Unpickling:
import pickle# open the file for reading
pic_in = open("mypicklefile", "rb")# load the object from the file into var a
a = pickle.load(pic_in)
print(a)Output:[1, 2, 3, 4, 5, 6, 7]
Use cases of 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).