Serialization In Python

Posted on 16th March, 2017 by Hetal Vinchhi
Serialization In Python

What is Serialization ?

Serialization is the process of converting data structure or object into a state that can be stored and can be reused for future use. This process is also called serializing or marshalling the object. The revert process is called deserialization or unmarshalling.

In python the process of serialization is achieved using the python module known as pickle. So what does the pickle do? Pickle stores the python objects into the byte stream in a file and unpickles the data back to the object form.

Pickle module has two methods called dump and load. The dump method is used to store the data from python object to the binary form. And the load method is used to store the data back from binary to the python object.

import pickle
fileName = "data.pkl"
d = {"name":"John","surname":"Smith","age":35}
l = ["sunday","monday","ttuesday","wednesday","thursday","friday","saturday"]

# Save data into file
print("Pickle Data into file")
with open(fileName,"wb") as pickleData:
    pickle.dump(d, pickleData)
    pickle.dump(l, pickleData)
print("Data Saved")

# Fetch data from file
print("Unpickle Data from file")
with open(fileName,"rb") as pickleData:
    d1 = pickle.load(pickleData)
    l1 = pickle.load(pickleData)
print("Data Retrived")

Output Serialization

In pickling and unpickling the data, it is important that if you using dump function more than one time then you have to use the load the function same times you have used the dump to retrieve the same amount of data you have stored.

Pickle follows a set of protocols in which it provides a standard way define, customize and control how your objects are serialized and deserialized.

Share Via:

Leave Comment

Assignment Solution Guru

Enter your Email ID to receive this Free Solution

We will not disclose your email address to anyone. Visit our Privacy Policy page for more information.

Thank You

Your download will start automatically...

Deals of the Day