To manipulate your files with pickle module, first you need to import it-
Pickling and Unpickling
The pickle module can take almost any python object and convert it to a string. This process is known as pickling. And the process of reconstructing the object from the string representation is called unpickling. Over the precess of pickling and unpickling, the string representation is stored either in a file or sent over a network connection to some other machine.
Methods of Pickling and Unpickling
Pickling and unpickling is so easy. Suppose, an object ‘x’ is to be writed to a file named ‘f’ which is opened for writing. Then the way to pickle the object is as follows-
To unpickle the object, the file object must be opened in writing mode. Then unpickling is done as follows-
The following examples demonstrate the method of pickling and unpickling-
import pickle filename="friendlist.data" friends=['pervej','arafat','amirul','imran','jewel'] f=open(filename,'wb') pickle.dump(friends,f) f.close()
In the example above, we have used pickle module to store the contents of a list into a file. A list named ‘friends’ is created and then we have opened a file in writing mode. Next, pickling is done. Finally we have closed the file. Now we will see how to unpickle the object and use it in another program.
import pickle filename="friendlist.data" f=open(filename,'rb') storedlist=pickle.load(f) print ("My friends are-") for i in storedlist: print(i)
My friends are-
To perform unpickling, again we must open the file. In this time, the file must be opened in reading mode. Then we have done unpickling and assign the contents of the file to a variable named “storedlist”. Thus we can use pickle module to store the objects and reuse it in another program.