What is pickling and unpickling in python?

Pickling and unpickling are very important when we have to transfer Python objects from one machine to another and vice versa. In this article, we will explain pickling and unpickling in Python with examples.

Pickling

In Python, pickling is the process by which Python objects are converted to byte streams. Pickling is about serializing the object structure in python.

Pickling Example


# Pickling in Python

import pickle

# Python object
my_list = [11, 'Python', b'Love Python']

# Pickling
with open("data.pickle","wb") as file_handle:
    pickle.dump(my_list, file_handle, pickle.HIGHEST_PROTOCOL)

print("Pickling completed!")

Output

Pickling completed!

This program creates data.pickle file in the current directory. Go and check for it :)

Pickle module (imported using import pickle) accepts any python objects and converts it into a string represesntation and dumps it into a file using a dump() method, this process is known as pickling.

Unpickling

Unpickling is the process of retrieving original python objects from the stored string representation i.e from the pickle file. It is the process of converting a byte stream into the python object.

Unpickling Example


# Unpickling in Python

import pickle

# Pickling
with open("data.pickle","rb") as file_handle:
    retrieved_data = pickle.load(file_handle)
    print(retrieved_data)

Output

[11, 'Python', b'Love Python']

For more detail about pickling and unpickling, we encourage you to check Python documentation for Pickle