Try it here
Pickling and Unpickling

Pickling and Unpickling in Python


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.

Pickle Example:

>>> 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 example:

>>> #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:

names = ['Ram', 'shaym', 'Lakhan', 'Sita']
ages = (30, 20, 15, 25)

Writer profile pic

Aditya on Apr 21, 2020 at 01:04 am

This article is contributed by Aditya. If you like and would like to contribute, you can write your article here or mail your article to . See your article appearing on the main page and help others to learn.

Post Comment

Comments( 0)




Forgot Password

Please enter your email address below and we will send you information to change your password.