Serialization and Deserialization with Python Pickle

Python pickle is a module used for serializing and deserializing objects in Python. It provides a mechanism for converting objects to binary streams and vice versa.

The process of converting objects into a sequence of bytes so that they can be stored in computer memory is called serialization. A serialized object is in the form of a stream or textual representation.

Deserialization on the other hand is the process of converting data (in the form of textual representation) into objects.

Python comes with a pickle module that enables you to serialize or deserialize data, otherwise known as pickling and unpickling.

Python Pickle dump

When you pickle an object, you convert it into a binary form before saving it in memory.

For instance:


import pickle

items = [1,2,3,4,5,6,7,8,9,10]

file = open('data.txt', 'wb')

pickle.dump(items, file)

The dump method in pickle is used to store binary data into a file.

Pickle load

When you unpickle data, you convert the data already in binary form into Python objects using the load method.


file = open('data.txt', 'rb')

reader = pickle.load(file)

print(reader)

#output

# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Leave a Reply

Your email address will not be published. Required fields are marked *