

{"id":125851,"date":"2023-11-15T12:44:06","date_gmt":"2023-11-15T07:14:06","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=125851"},"modified":"2024-02-29T14:06:21","modified_gmt":"2024-02-29T08:36:21","slug":"python-program-for-pickle-module","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/","title":{"rendered":"Python Program for Pickle Module"},"content":{"rendered":"<p>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.<\/p>\n<p>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.<\/p>\n<h2>Topic Explanation:<\/h2>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>By the end of this tutorial, you&#8217;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.<\/p>\n<h3>Prerequisites:<\/h3>\n<ul>\n<li>Basic understanding of Python programming language.<\/li>\n<li>Familiarity with basic data types and data structures in Python.<\/li>\n<li>Python installed on your machine.<\/li>\n<li>A text editor or an integrated development environment (IDE) for writing and executing Python code.<\/li>\n<li>Curiosity and interest in exploring data serialization and persistence concepts.<\/li>\n<\/ul>\n<h3>Code 1 with Comments:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Defining a class named \"Student\"\r\nclass Student:\r\n    \r\n    # Constructor method \"__init__\" initializes the object with attributes\r\n    def __init__(self, rno, name, course):\r\n        # Assigning values to object attributes\r\n        self.rno = rno\r\n        self.name = name\r\n        self.course = course\r\n\r\n    # Method \"display\" prints information about the student\r\n    def display(self):\r\n        print(\"Roll No:\", self.rno)\r\n        print(\"Name:\", self.name)\r\n        print(\"Course:\", self.course)<\/pre>\n<p><strong>Output For code 1:<\/strong><\/p>\n<p>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.<\/p>\n<h3>Code 1 Explanation:<\/h3>\n<ul>\n<li><strong>class Student::<\/strong> Defines a class named &#8220;Student&#8221; to represent student objects.<\/li>\n<li><strong>def __init__(self, rno, name, course)::<\/strong> Defines the constructor method &#8220;init&#8221; that initializes the object with attributes.<\/li>\n<li><strong>self.rno = rno:<\/strong> Assigns the value of the parameter &#8220;rno&#8221; to the object&#8217;s &#8220;rno&#8221; attribute.<\/li>\n<li><strong>self.name = name:<\/strong> Assigns the value of the parameter &#8220;name&#8221; to the object&#8217;s &#8220;name&#8221; attribute.<\/li>\n<li><strong>self.course = course:<\/strong> Assigns the value of the parameter &#8220;course&#8221; to the object&#8217;s &#8220;course&#8221; attribute.<\/li>\n<li><strong>def display(self)::<\/strong> Defines a method named &#8220;display&#8221; that prints information about the student.<\/li>\n<li><strong>print(&#8220;Roll No:&#8221;, self.rno):<\/strong> Prints the roll number of the student.<\/li>\n<li><strong>print(&#8220;Name:&#8221;, self.name):<\/strong> Prints the name of the student.<\/li>\n<li><strong>print(&#8220;Course:&#8221;, self.course):<\/strong> Prints the course of the student.<\/li>\n<\/ul>\n<h3>Code 2 with Comments:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Importing the \"student\" module (presumably containing the Student class)\r\nimport pickle\r\nimport student\r\n\r\n# Using a try-except block to handle potential errors\r\ntry:\r\n    # Opening a file named \"studentrecord.txt\" for writing in binary mode\r\n    f = open(\"c:\/\/myfile\/studentrecord.txt\", \"wb\")\r\n\r\n    # Checking if the file is writable\r\n    if f.writable():\r\n        # Getting user input for student information\r\n        sno = int(input(\"Enter Roll No: \"))\r\n        sname = input(\"Enter Name: \")\r\n        scourse = input(\"Enter Course: \")\r\n\r\n        # Creating an instance of the Student class with the user input\r\n        S1 = student.Student(sno, sname, scourse)\r\n\r\n        # Using Pickle to dump (serialize) the Student object into the file\r\n        pickle.dump(S1, f)\r\n\r\n        # Printing a success message\r\n        print(\"File Created........\")\r\n\r\n        # Closing the file\r\n        f.close()\r\n\r\n# Handling exceptions and printing the error message\r\nexcept Exception as msg:\r\n    print(msg)<\/pre>\n<p><strong>Output For code 2:<\/strong><\/p>\n<p>The program doesn&#8217;t provide direct output but creates a binary file named &#8220;studentrecord.txt&#8221; containing the serialized student object using Pickle. The success message &#8220;File Created&#8230;&#8230;..&#8221; is printed if the operation is successful.<\/p>\n<h3>Code 2 Explanation<\/h3>\n<ul>\n<li><strong>import pickle:<\/strong> Imports the pickle module, which provides a way to serialize and deserialize Python objects.<\/li>\n<li><strong>import student:<\/strong> Imports the &#8220;student&#8221; module, presumably containing the Student class.<\/li>\n<li><strong>try::<\/strong> Starts a try block to handle potential exceptions.<\/li>\n<li><strong>f = open(&#8220;c:\/\/myfile\/studentrecord.txt&#8221;, &#8220;wb&#8221;):<\/strong> Opens a file named &#8220;studentrecord.txt&#8221; for writing in binary mode and assigns the file handle to the variable f.<\/li>\n<li><strong>if f.writable()::<\/strong> Checks if the file is writable.<\/li>\n<li><strong>sno = int(input(&#8220;Enter Roll No: &#8220;)):<\/strong> Gets user input for the student&#8217;s roll number and converts it to an integer.<\/li>\n<li><strong>sname = input(&#8220;Enter Name: &#8220;):<\/strong> Gets user input for the student&#8217;s name.<\/li>\n<li><strong>scourse = input(&#8220;Enter Course: &#8220;):<\/strong> Gets user input for the student&#8217;s course.<\/li>\n<li><strong>S1 = student.Student(sno, sname, scourse):<\/strong> Creates an instance of the Student class with the user input.<\/li>\n<li><strong>pickle.dump(S1, f):<\/strong> Uses Pickle to dump (serialize) the Student object into the file.<\/li>\n<li><strong>print(&#8220;File Created&#8230;&#8230;..&#8221;):<\/strong> Prints a success message.<\/li>\n<li><strong>f.close():<\/strong> Closes the file.<\/li>\n<li><strong>except Exception as msg::<\/strong> Starts an except block to handle exceptions, and assigns the exception message to the variable msg.<\/li>\n<li><strong>print(msg):<\/strong> Prints the error message.<\/li>\n<\/ul>\n<h3>Code 3 with Comments:<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\"># Importing the \"pickle\" module for object serialization and the \"student\" module (presumably containing the Student class)\r\nimport pickle\r\nimport student\r\n\r\n# Importing the \"os\" module for interacting with the operating system\r\nimport os\r\n\r\n# Using a try-except block to handle potential errors\r\ntry:\r\n    # Setting the file path to \"c:\/\/myfile\/studentrecord.txt\"\r\n    file_path = \"c:\/\/myfile\/studentrecord.txt\"\r\n    \r\n    # Checking if the file exists\r\n    if os.path.isfile(file_path):\r\n        \r\n        # Opening the file for reading in binary mode\r\n        f = open(file_path, \"rb\")\r\n        \r\n        # Checking if the file is readable\r\n        if f.readable():\r\n            \r\n            # Loading (deserializing) the object from the file using Pickle\r\n            S = pickle.load(f)\r\n            \r\n            # Calling the \"display\" method of the Student class to print student information\r\n            S.display()\r\n            \r\n            # Printing the object itself (Note: The __str__ method in the Student class would be called)\r\n            print(S)\r\n            \r\n            # Closing the file\r\n            f.close()\r\n\r\n# Handling exceptions and printing the error message\r\nexcept Exception as obj:\r\n    print(obj)<\/pre>\n<p><strong>Code 3 Output:<\/strong><\/p>\n<p>The program reads the serialized student object from the file &#8220;studentrecord.txt&#8221; 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.<br \/>\nStill we have can consider the demo output as follows:<\/p>\n<p><strong>Roll No:<\/strong> 101<br \/>\n<strong>Name:<\/strong> John Doe<br \/>\n<strong>Course:<\/strong> Computer Science<br \/>\n&lt;student.Student object at 0xXXXXXXXX&gt;<\/p>\n<p>The last line, &lt;student.Student object at 0xXXXXXXXX&gt;, is the default representation of the Student object.<\/p>\n<h3>Code 3 Explanation:<\/h3>\n<ul>\n<li><strong>import pickle:<\/strong> Imports the pickle module for object serialization and deserialization.<\/li>\n<li><strong>import student:<\/strong> Imports the &#8220;student&#8221; module, presumably containing the Student class.<\/li>\n<li><strong>import os:<\/strong> Imports the os module for interacting with the operating system.<\/li>\n<li><strong>try::<\/strong> Starts a try block to handle potential exceptions.<\/li>\n<li><strong>file_path = &#8220;c:\/\/myfile\/studentrecord.txt&#8221;:<\/strong> Sets the file path to &#8220;c:\/\/myfile\/studentrecord.txt&#8221;.<\/li>\n<li><strong>if os.path.isfile(file_path)::<\/strong> Checks if the file exists at the specified path.<\/li>\n<li><strong>f = open(file_path, &#8220;rb&#8221;):<\/strong> Opens the file for reading in binary mode and assigns the file handle to the variable f.<\/li>\n<li><strong>if f.readable()::<\/strong> Checks if the file is readable.<\/li>\n<li><strong>S = pickle.load(f):<\/strong> Loads (deserializes) the object from the file using Pickle.<\/li>\n<li><strong>S.display():<\/strong> Calls the &#8220;display&#8221; method of the Student class to print student information.<\/li>\n<li><strong>print(S):<\/strong> Prints the object itself (Note: The __str__ method in the Student class would be called).<\/li>\n<li><strong>f.close():<\/strong> Closes the file.<\/li>\n<li><strong>except Exception as obj::<\/strong> Starts an except block to handle exceptions, and assigns the exception message to the variable obj.<\/li>\n<li><strong>print(obj):<\/strong> Prints the error message.<\/li>\n<\/ul>\n<h3>Conclusion:<\/h3>\n<p>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&#8217;s skill set but also expands their proficiency in efficiently managing and manipulating data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46],"tags":[28921,10333,28922,28626,28920],"class_list":["post-125851","post","type-post","status-publish","format-standard","hentry","category-python","tag-pickle-module-in-python","tag-python","tag-python-pickle-module","tag-python-practical","tag-python-program-on-pickle-module"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Python Program for Pickle Module - DataFlair<\/title>\n<meta name=\"description\" content=\"Python program serves as a testament to the prowess of the Pickle module in serializing and deserializing objects.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python Program for Pickle Module - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Python program serves as a testament to the prowess of the Pickle module in serializing and deserializing objects.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-11-15T07:14:06+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-02-29T08:36:21+00:00\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python Program for Pickle Module - DataFlair","description":"Python program serves as a testament to the prowess of the Pickle module in serializing and deserializing objects.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/","og_locale":"en_US","og_type":"article","og_title":"Python Program for Pickle Module - DataFlair","og_description":"Python program serves as a testament to the prowess of the Pickle module in serializing and deserializing objects.","og_url":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-11-15T07:14:06+00:00","article_modified_time":"2024-02-29T08:36:21+00:00","author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Python Program for Pickle Module","datePublished":"2023-11-15T07:14:06+00:00","dateModified":"2024-02-29T08:36:21+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/"},"wordCount":1050,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"keywords":["pickle module in python","Python","python pickle module","python practical","python program on pickle module"],"articleSection":["Python Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/","url":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/","name":"Python Program for Pickle Module - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"datePublished":"2023-11-15T07:14:06+00:00","dateModified":"2024-02-29T08:36:21+00:00","description":"Python program serves as a testament to the prowess of the Pickle module in serializing and deserializing objects.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/python-program-for-pickle-module\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Python Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/python\/"},{"@type":"ListItem","position":3,"name":"Python Program for Pickle Module"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"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.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125851","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=125851"}],"version-history":[{"count":3,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125851\/revisions"}],"predecessor-version":[{"id":134273,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/125851\/revisions\/134273"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=125851"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=125851"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=125851"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}