In Python, Pickling is a process where a python object is converted into a byte stream and dumps it into a file by using dump() function. It is used for serializing and deserializing a Python object structure. This process converts all python objects into byte streams which means 0s and 1s are known as pickling or serializing. This process is also called as flattening or marshaling.
The reverse operation of this process is called unpickling, which means it converts byte stream back into python objects. It can be done by using the function loads() in python. The character stream produced due to the Pickling process contains all the information necessary to reconstruct the object in another python script.
The application of Pickling and unpickling are mostly used as they allow transferring data easily from one system to another and then stores it in file or database.
To perform the Pickling process, we need to import it in Python.
In this pickle, there are two functions loads() and dumps() which are used to load an object from file and dump file into an object respectively.
Pickling Python Code:
import pickle data= [‘python’, ‘java’, ‘c’, ‘c++’] with open(‘filename.txt’, ‘w’) as file: pickle.dump(data, file)
Unpickling Python Code:
import pickle new_data=open(‘filename.txt’, ‘r’) text=pickle.load(new_data) text
Merits of Pickle
- Pickle saves the program state data to disk, where the data is saved to access and continue from where it left off.
- It stores the python objects in the database.
- It sends the python data in a multi-core or distributed system over TCP connection.
- It can convert an arbitrary python object to a string that can be used as a dictionary key.
- It does not require several lines of code which is easy to use.
- The pickled file is not easily readable through which it can provide some security.