Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it "serializes" the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script.
>>> import pickle >>> #pickling example >>> #prepare data list or tuple to be store into the file >>> list1=["Ram","shaym","Lakhan","Sita"] >>> tuple1=(30,20,15,25) >>> dict1={} >>> dict1["names"]=list1 >>> dict1["ages"]=tuple1 >>> #Now open a file to dump these data, its important to open the file in binary mode >>> pickfile=open("pickledData.txt","ab") >>> pickle.dump(dict1,pickfile)# source,target >>> pickfile.close() >>>
>>> #unpickle >>> dict1=open("pickledData.txt","rb") # its important to open in binary mode >>> pickfile=open("pickledData.txt","rb") # its important to open in binary mode >>> dict1=pickle.load(pickfile) >>> for k in dict1: print(k,"=",dict1[k]) names = ['Ram', 'shaym', 'Lakhan', 'Sita'] ages = (30, 20, 15, 25) >>>
This article is contributed by Aditya. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.