TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Serializing Python Objects Using Pickle
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python OOPPython Tutorials

Serializing Python Objects Using Pickle

Last updated: Nov 05, 2023 6:30 pm
By Harsh S.
Share
7 Min Read
Python Tutorial - Serializing Python Objects Using Pickle
Serializing Python Objects.
SHARE

Welcome to the Python tutorial, today we’ll dive into the concept of serializing Python objects. Serialization is a universal concept and almost all the programming languages provide the mechanism to implement it. In this post, we’ll thoroughly explain the step-by-step process for enabling the Serialization of Python objects.

Contents
What is Pickle and how to use it?What data type can the Pickle module store?How to use the Pickle library for serializing Python objects?

Introduction to Serialization

In object-oriented programming, Serialization is the process of transforming data structures or objects into a format that can be offloaded to a file, or memory cache or transmitted over the network connection and the same object can be reconstructed later in the same or different environment.

Serialization is converting the object into a stream of bytes also called marshaling an object, and the reverse process of rebuilding the object back from the stream of bytes is deserialization or unmarshalling.

The process of Serializing Python Objects

Python Tutorial - Serializing Python Objects Using Pickle
Serializing Python Objects

In Python, serialization and deserialization are achieved through the “Pickle” library.

What is Pickle and how to use it?

Pickle library is developed using the C programming language like the Python interpreter is. It can save arbitrarily complex Python data structures. Pickle is extensible, cross-version, and not very secure (not secure against erroneous or maliciously constructed data).

What data type can the Pickle module store?

The pickle module stores the following data types:

  • All the native data types that Python maintains: Booleans, integers, floating point numbers, complex numbers, strings, byte objects, byte arrays, and None.
  • Lists, tuples, dictionaries, and sets holding any sequence of native data types.
  • Lists, dictionaries, tuples, and sets with the following variations.
    • Sets carrying any combination of lists/tuples/dictionaries, and
    • Sets enclosing any combination of native data types (and so on, to the maximum nesting level that Python allows).
  • Functions, classes, and the instances of classes (with limitations).

Pickle has two primary methods. The first one is a dump that drops an object to a file. The second method is the load that loads the object from a file object.

How to use the Pickle library for serializing Python objects?

Step#1 Construct Pickle Data.

We will use dictionary-type data for pickling that contains the information related to our website:

website = {'title' : 'Techbeamers', 'site_link' : '/','site_type': 'technology blog','owner':'Python Serialization tutorial','established_date':'Sep2015'}
Step#2 Saving data as a pickle file

Now, we have a dictionary that has all the information about the website. Let’s save it as a pickle file:

import pickle
with open ('website.pickle','wb') as f:
    pickle.dump(website,f)
  • We’ve used the “wb” file mode to open the file in binary mode for the write operation.
  • Enclose it using a “with” statement to make sure the file is automatically closed after we are done with it.
  • The dump() method in the pickle module takes a serializable Python data structure, in this case, the dictionary created by us and performs the following operation.
    • Serializes it into a binary format using the latest version of the pickle protocol.
    • Saves it to an open file.
  • For your information, the pickle is a protocol that is Python-centric. There is no surety of cross-language compatibility.
  • The most recent version of the pickle protocol requires a binary format. So, please make sure to open the pickle files only in binary mode. Otherwise, the data will get corrupted while writing.
Step#3 Loading data from the Pickle file

Following is a piece of code that will load the data from the pickle file.

import pickle
with open ('website.pickle', 'rb') as f:
    data = pickle.load(f)
    print (data)
Output:
{'site_link': '/', 'title': 'Techbeamers', 'owner': 'Python Serialization tutorial', 'established_date': 'Sep2015', 'site_type': 'technology blog'}
  • From the above code fragment, you can check that we’ve opened the ‘website.pickle’ file that was created after formatting the Python dictionary data type.
  • Since the pickle module supports the binary data format, we’ve opened the pickle file in binary mode.
  • The pickle.load() method accepts the stream object as a parameter and performs the following operations.
    • Scans the serialized buffer from the stream.
    • Instantiate a brand-new Python object.
    • Rebuilds the new Python object using the serialized data, and returns the renewed object.
  • The pickle.dump() and pickle.load() cycle forms a new data structure that is identical to the original data structure.

In the end, we’ve consolidated all the pieces of the code mentioned above and presented the unified structure below.

import pickle

website = {'title' : 'Techbeamers', 'site_link' : '/','site_type': 'technology blog','owner':'Python Serialization tutorial','established_date':'Sep2015'}

with open ('website.pickle','wb') as f:
    pickle.dump(website,f)

with open ('website.pickle', 'rb') as f:
    data = pickle.load(f)
    print (data)

So, that was all we wanted to convey about the Serialization concept in Python. Hope you would have liked it.

Next, we had a number of Python tutorials/quizzes/interview questions on this blog. If you like to try them, please just go ahead.

You might wanna check out our tutorial on Python Class Methods.

Final word

We always try to cover concepts that are important from the language perspective and crucial for the interview purpose. That’s why we delivered this post on serializing Python objects. If you want us to cover any topic of your choice, then please send us your request using the comment box section.

If this post was able to gain your attention, then please do share this article on social media and with your friends.

Keep Reading & Continue Improving,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Essential Java Collection Interview Questions Java Collection Interview Questions (2024)
Next Article Python Socket Programming Explained in a NutShell Essentials of Python Socket Programming

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x