Tutorial

Python Pickle Example

Published on August 3, 2022
Default avatar

By Pankaj

Python Pickle Example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this tutorial we will be discussing about Python Pickle Example. In our previous tutorial, we discussed about Python Multiprocessing.

Python Pickle

Python Pickle is used to serialize and deserialize a python object structure. Any object on python can be pickled so that it can be saved on disk. At first Python pickle serialize the object and then converts the object into a character stream so that this character stream contains all the information necessary to reconstruct the object in another python script. Note that the pickle module is not secure against erroneous or maliciously constructed data according to the documentation. So, never unpickle data received from an untrusted or unauthenticated source.

Python Pickle dump

In this section, we are going to learn, how to store data using Python pickle. To do so, we have to import the pickle module first. Then use pickle.dump() function to store the object data to the file. pickle.dump() function takes 3 arguments. The first argument is the object that you want to store. The second argument is the file object you get by opening the desired file in write-binary (wb) mode. And the third argument is the key-value argument. This argument defines the protocol. There are two type of protocol - pickle.HIGHEST_PROTOCOL and pickle.DEFAULT_PROTOCOL. See the sample code to know how to dump data using pickle.

import pickle

# take user input to take the amount of data
number_of_data = int(input('Enter the number of data : '))
data = []

# take input of the data
for i in range(number_of_data):
    raw = input('Enter data '+str(i)+' : ')
    data.append(raw)

# open a file, where you ant to store the data
file = open('important', 'wb')

# dump information to that file
pickle.dump(data, file)

# close the file
file.close()

The following program will prompt you to enter some input. In my case, it was like this. python pickle dump

Python Pickle load

To retrieve pickled data, the steps are quite simple. You have to use pickle.load() function to do that. The primary argument of pickle load function is the file object that you get by opening the file in read-binary (rb) mode. Simple! Isn’t it. Let’s write the code to retrieve data we pickled using the pickle dump code. See the following code for understanding.

import pickle

# open a file, where you stored the pickled data
file = open('important', 'rb')

# dump information to that file
data = pickle.load(file)

# close the file
file.close()

print('Showing the pickled data:')

cnt = 0
for item in data:
    print('The data ', cnt, ' is : ', item)
    cnt += 1

The output will be the following:

Showing the pickled data:
The data  0  is :  123
The data  1  is :  abc
The data  2  is :  !@#$

Python Pickle Example

I made a short video showing execution of python pickle example programs - first to store data into file and then to load and print it. python pickle example As you can see that the file created by python pickle dump is a binary file and shows garbage characters in the text editor.

Important Notes on Python Pickle

Few important points about python pickle module are:

  1. The pickle protocol is specific to Python - it’s not guaranteed to be cross-language compatible. This means you most likely can’t transfer the information to make it useful in other programming languages.
  2. There is also no guarantee of compatibility between different versions of Python because not every Python data structure can be serialized by the module.
  3. The latest version of the pickle protocol is used by default unless you manually change it.
  4. Last but not least, the pickle module is not secure against erroneous or maliciously constructed data according to the documentation.

So, that’s all about python pickle example. Hope that you understand well. For any further query please use the comment section. :) Reference: Official Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 17, 2021

Import pickle f1=open(“emp.dat”,“rb”) e=pickle.load(f1) for x in___:#line1 if(e[x]>=25000 and e[x]>=30000 print(x) f1.close() What should be written in line 1?

- Siddharth

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 15, 2020

    Thanks man, your tutorial is AWESOME.

    - Aryan

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 11, 2020

      Well explained! Thankyou

      - Johan

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 9, 2020

        # dump information to that file should be # load information from that file

        - bruh

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 19, 2020

          thanks man

          - aditya m

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 22, 2019

            Thank you for clear telling.

            - halil

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 4, 2019

              Your tutorials are awesome, thank you.

              - Robert

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                December 26, 2017

                if i want to enter the data as in a dictionary and store using8 pickle?how will i do it?

                - joshy

                  Try DigitalOcean for free

                  Click below to sign up and get $200 of credit to try our products over 60 days!

                  Sign up

                  Join the Tech Talk
                  Success! Thank you! Please check your email for further details.

                  Please complete your information!

                  Get our biweekly newsletter

                  Sign up for Infrastructure as a Newsletter.

                  Hollie's Hub for Good

                  Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                  Become a contributor

                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                  Welcome to the developer cloud

                  DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                  Learn more
                  DigitalOcean Cloud Control Panel