DEV Community

Ngotho
Ngotho

Posted on

What is Pickle in python ?

It is used for serializing and de-serializing a Python object structure.
Pickling: It is a process where a Python object hierarchy is converted into a byte stream and dumps it into a file by using dump function.This character stream contains all the information necessary to reconstruct the object in another python script.

Unpickling: It is the inverse of Pickling process where a byte stream is converted into an object hierarchy.While the process of retrieving original Python objects from the stored string representation is called unpickling.we use load function to do this.
First of all you have to import pickle module through this command:

import pickle
Pickle has two main methods. The first one is dump, which dumps an object to a file object and the second one is load, which loads an object from a file object.

Examples
1). Pickling.
import pickle

a=[1, 2, 3, 4, 5, 6, 7]

open the file for writing

pic_out=open("mypicklefile","wb")

write object to file mypicklefile

pickle.dump(a,pic_out)

pic_out.close()
2). Unpickling.
import pickle

open the file for reading

pic_in = open("mypicklefile", "rb")

load the object from the file into var a

a = pickle.load(pic_in)

print(a)
Output:[1, 2, 3, 4, 5, 6, 7]
Use cases of Pickling:

saving a program’s state data to disk so that it can carry on where it left off when restarted (persistence)
sending python data over a TCP connection in a multi-core or distributed system (marshalling)
storing python objects in a database
converting an arbitrary python object to a string so that it can be used as a dictionary key (e.g. for

AWS Industries LIVE! Stream

Business benefits of the cloud

Join AWS experts and tech leaders as they discuss the business impact of the cloud on Industries LIVE!

Learn More

Top comments (0)

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay