In the previous chapter, Files in Python, we looked at the basic file operations you can perform using Python. However, if you want to store and retrieve the structured data, you can do it easily using a concept called Pickle in Python.
Please do not get confused about the programs mentioned below. You will find their explanations after the programs. For better convenience and understanding, we thought writing the programs first for you would be correct.
Let us understand Pickle in Python using an example. Save the code mentioned below as Student.py.
#save this file as Student.py
class Student:
def __init__(self, rollno, name, marks):
self.rollno = rollno
self.name = name
self.marks = marks
def display(self):
print("Name is: ",self.name)
print("Roll No is: ",self.rollno)
print("Marks: ",self.marks)
Create another program that has the logic to import the Student class objects into a new dat file, ‘stu.dat’. Save the below program as pickle_example.py
#Python program to show the concept of pickle
import Student, pickle
#create a new dat file in write binary mode
f = open('stu.dat','wb')
num = int(input("How many students? "))
for i in range(num):
rollno = int(input("Enter rollno: "))
name = input("Enter name: ")
marks = int(input("Enter marks: "))
#create an object for Student class
s = Student.Student(rollno,name,marks)
#store the object into the file now
pickle.dump(s,f)
#close the file
f.close()
How many students? 2
Enter rollno: 23
Enter name: Sudheer
Enter marks: 30
Enter rollno: 34
Enter name: Shabari
Enter marks: 35
In the programs above, we created first a Student Class and stored it in the Student.py file. This class contains a constructor method that initializes the rollno, name, and marks, and another method called display() which prints these values on the screen.
We then created another program, pickle_example.py, that imports this Student class and pickle module. In this program, we created a new file called ‘stu.dat‘ by opening it in binary writing mode. We then added a logic to enter the details of students based on the number of students.
‘s=Student.Student(rollno,name,marks)‘ creates a separate object for each student during each iteration by passing the values of rollno, name, and marks. Eventually, we pickle this object into the file using pickle.dump(s,f). Here’ s‘ is the object during each iteration, and ‘f‘ is the file handler of the ‘stu.dat‘ file in this program.
The pickle module’s dump() method helps write the data into the file. You can see from the console output above that we tried entering the details of two students. The data of both the students are saved in the dat file.
Let us try retrieving this same data from the ‘stu.dat‘ file using another Python program.
#Python program to unpickle the data
import Student, pickle
#opening file in the binary read mode
f = open('stu.dat','rb')
print('Student details: ')
while True:
try:
#read objects from the file f
obj_val = pickle.load(f)
#display the values from the object
obj_val.display()
except EOFError:
print("File has reached the end..")
break
f.close() #closing the file
Output:
Student details:
Name is: Sudheer
Roll No is: 23
Marks: 30
Name is: Shabari
Roll No is: 34
Marks: 35
File has reached the end..
In the above program, we opened the same dat file, ‘stu.dat‘, in binary read mode. We then tried loading the data of each object using the pickle.load() method in a while loop. You can see from the output above that it has printed precisely the same values that we had entered. This concept of retrieving data is called unpickling the data.
We hope you have understood the concept of Pickle and Unpickle in Python.