Page 1 of 1

File Manipulations with pickle Module Demonstrates how to manipulate files with complex data structures in P

#1 atik97  Icon User is offline

  • ???
  • member icon

Reputation: 144
  • View blog
  • Posts: 715
  • Joined: 16-September 08

Posted 27 January 2009 - 11:11 AM

You can save your works with files. It works nicely for strings. If you want to work with numbers or data structures like lists, tuples or dictionaries, then things become so complicated that need an alternative. Python provides a standard module named pickle which can be used to store any python object to a file and then get it back later.Let’s see how to manipulate file with pickle module-

To manipulate your files with pickle module, first you need to import it-

import pickle



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-

pickle.dump(x,f)



To unpickle the object, the file object must be opened in writing mode. Then unpickling is done as follows-

x=pickle.load(f)



The following examples demonstrate the method of pickling and unpickling-

Example:Pickling
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.

Example:Unpickling
import pickle
filename="friendlist.data"
f=open(filename,'rb')
storedlist=pickle.load(f)
print ("My friends are-")
for i in storedlist:
	print(i) 



Output:

My friends are-
pervej
arafat
amirul
imran
jewel

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.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1