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:

  • Basic understanding of Python programming language.
  • Familiarity with basic data types and data structures in Python.
  • Python installed on your machine.
  • A text editor or an integrated development environment (IDE) for writing and executing Python code.
  • Curiosity and interest in exploring data serialization and persistence concepts.

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:

  • class Student:: Defines a class named “Student” to represent student objects.
  • def __init__(self, rno, name, course):: Defines the constructor method “init” that initializes the object with attributes.
  • self.rno = rno: Assigns the value of the parameter “rno” to the object’s “rno” attribute.
  • self.name = name: Assigns the value of the parameter “name” to the object’s “name” attribute.
  • self.course = course: Assigns the value of the parameter “course” to the object’s “course” attribute.
  • def display(self):: Defines a method named “display” that prints information about the student.
  • print(“Roll No:”, self.rno): Prints the roll number of the student.
  • print(“Name:”, self.name): Prints the name of the student.
  • print(“Course:”, self.course): Prints the course of the student.

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

  • import pickle: Imports the pickle module, which provides a way to serialize and deserialize Python objects.
  • import student: Imports the “student” module, presumably containing the Student class.
  • try:: Starts a try block to handle potential exceptions.
  • f = open(“c://myfile/studentrecord.txt”, “wb”): Opens a file named “studentrecord.txt” for writing in binary mode and assigns the file handle to the variable f.
  • if f.writable():: Checks if the file is writable.
  • sno = int(input(“Enter Roll No: “)): Gets user input for the student’s roll number and converts it to an integer.
  • sname = input(“Enter Name: “): Gets user input for the student’s name.
  • scourse = input(“Enter Course: “): Gets user input for the student’s course.
  • S1 = student.Student(sno, sname, scourse): Creates an instance of the Student class with the user input.
  • pickle.dump(S1, f): Uses Pickle to dump (serialize) the Student object into the file.
  • print(“File Created……..”): Prints a success message.
  • f.close(): Closes the file.
  • except Exception as msg:: Starts an except block to handle exceptions, and assigns the exception message to the variable msg.
  • print(msg): Prints the error message.

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:

  • import pickle: Imports the pickle module for object serialization and deserialization.
  • import student: Imports the “student” module, presumably containing the Student class.
  • import os: Imports the os module for interacting with the operating system.
  • try:: Starts a try block to handle potential exceptions.
  • file_path = “c://myfile/studentrecord.txt”: Sets the file path to “c://myfile/studentrecord.txt”.
  • if os.path.isfile(file_path):: Checks if the file exists at the specified path.
  • f = open(file_path, “rb”): Opens the file for reading in binary mode and assigns the file handle to the variable f.
  • if f.readable():: Checks if the file is readable.
  • S = pickle.load(f): Loads (deserializes) the object from the file using Pickle.
  • S.display(): Calls the “display” method of the Student class to print student information.
  • print(S): Prints the object itself (Note: The __str__ method in the Student class would be called).
  • f.close(): Closes the file.
  • except Exception as obj:: Starts an except block to handle exceptions, and assigns the exception message to the variable obj.
  • print(obj): Prints the error message.

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.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *