Site icon DataFlair

Python Program for Pickle Module

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Embarking on the practical side of Python programming, this tutorial delves into the Python Pickle module, offering a hands-on exploration of creating a Python program that utilizes Pickle. Pickle is a powerful module that enables the serialization and deserialization of Python objects, facilitating the storage and retrieval of complex data structures.

In this tutorial, we will unravel the capabilities of the Pickle module, demonstrating how it can be employed to save and load Python objects, fostering a deeper understanding of data persistence and manipulation.

Topic Explanation:

In this exploration, we will delve into the development of a Python program that harnesses the capabilities of the Pickle module. The first step involves understanding the serialization process, where Python objects are converted into a byte stream for storage or transmission. Through practical examples, we will showcase how to use Pickle to save objects to a file, preserving their structure and state.

Subsequently, we will explore the deserialization process, retrieving the original objects from the stored byte stream. The program will emphasize the flexibility of Pickle in handling diverse data types and structures, making it a valuable tool for developers dealing with complex data persistence requirements.

By the end of this tutorial, you’ll have gained practical insights into working with the Pickle module, empowering you to implement efficient data storage and retrieval mechanisms in your Python applications.

Prerequisites:

Code 1 with Comments:

# Defining a class named "Student"
class Student:
    
    # Constructor method "__init__" initializes the object with attributes
    def __init__(self, rno, name, course):
        # Assigning values to object attributes
        self.rno = rno
        self.name = name
        self.course = course

    # Method "display" prints information about the student
    def display(self):
        print("Roll No:", self.rno)
        print("Name:", self.name)
        print("Course:", self.course)

Output For code 1:

No output is generated by the class definition alone. The class serves as a blueprint for creating instances of student objects. To see the output, instances of the Student class need to be created and methods need to be called on those instances.

Code 1 Explanation:

Code 2 with Comments:

# Importing the "student" module (presumably containing the Student class)
import pickle
import student

# Using a try-except block to handle potential errors
try:
    # Opening a file named "studentrecord.txt" for writing in binary mode
    f = open("c://myfile/studentrecord.txt", "wb")

    # Checking if the file is writable
    if f.writable():
        # Getting user input for student information
        sno = int(input("Enter Roll No: "))
        sname = input("Enter Name: ")
        scourse = input("Enter Course: ")

        # Creating an instance of the Student class with the user input
        S1 = student.Student(sno, sname, scourse)

        # Using Pickle to dump (serialize) the Student object into the file
        pickle.dump(S1, f)

        # Printing a success message
        print("File Created........")

        # Closing the file
        f.close()

# Handling exceptions and printing the error message
except Exception as msg:
    print(msg)

Output For code 2:

The program doesn’t provide direct output but creates a binary file named “studentrecord.txt” containing the serialized student object using Pickle. The success message “File Created……..” is printed if the operation is successful.

Code 2 Explanation

Code 3 with Comments:

# Importing the "pickle" module for object serialization and the "student" module (presumably containing the Student class)
import pickle
import student

# Importing the "os" module for interacting with the operating system
import os

# Using a try-except block to handle potential errors
try:
    # Setting the file path to "c://myfile/studentrecord.txt"
    file_path = "c://myfile/studentrecord.txt"
    
    # Checking if the file exists
    if os.path.isfile(file_path):
        
        # Opening the file for reading in binary mode
        f = open(file_path, "rb")
        
        # Checking if the file is readable
        if f.readable():
            
            # Loading (deserializing) the object from the file using Pickle
            S = pickle.load(f)
            
            # Calling the "display" method of the Student class to print student information
            S.display()
            
            # Printing the object itself (Note: The __str__ method in the Student class would be called)
            print(S)
            
            # Closing the file
            f.close()

# Handling exceptions and printing the error message
except Exception as obj:
    print(obj)

Code 3 Output:

The program reads the serialized student object from the file “studentrecord.txt” and displays the student information using the display method of the Student class. Additionally, it prints the object itself, which will invoke the __str__ method of the Student class.
Still we have can consider the demo output as follows:

Roll No: 101
Name: John Doe
Course: Computer Science
<student.Student object at 0xXXXXXXXX>

The last line, <student.Student object at 0xXXXXXXXX>, is the default representation of the Student object.

Code 3 Explanation:

Conclusion:

In summary, this Python program serves as a testament to the prowess of the Pickle module in serializing and deserializing objects. Through the act of saving a Student object to a file, followed by its subsequent loading and information display, the program vividly illustrates the practicality of data persistence. Pickle, with its ability to simplify the storage of complex Python objects, emerges as an invaluable tool for applications demanding seamless data retention between program executions. The incorporation of such serialization techniques not only enriches a programmer’s skill set but also expands their proficiency in efficiently managing and manipulating data.

Exit mobile version