In this blog, we will serialize list, dictionary, method and class ojbect with pickle module. After that we will deserialize them also.
The pickle module implements binary protocols for serializing and de-serializing a Python object structure.
"Pickling" is the process whereby a Python object hierarchy is converted into a byte stream, and "unpickling" is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.
Pickling and unpickling are known as "serialization" and "deserialization".
To serialize an object, simply we have to call the dumps() function. Similarly, to de-serialize a data stream, we have to call the loads() function.
The pickle module keeps track of the objects it has already serialized, so that later references to the same object won’t be serialized again.
What can be pickled and unpickled?
The following types can be pickled:
- None, True, and False
- integers, floating point numbers, complex numbers
- strings, bytes, bytearrays
- tuples, lists, sets, and dictionaries containing only picklable objects
- functions defined at the top level of a module (using def, not lambda)
- built-in functions defined at the top level of a module
- classes that are defined at the top level of a module
import pickle
dict1 = {1: "John", 2: "Martha", 3:"Monalisa", 4: "Priyanka", 5: "Sheron"}
dict1
open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode.
The available modes are:
'r': open for reading (default)
'w': open for writing, truncating the file first
'x': open for exclusive creation, failing if the file already exists
'a': open for writing, appending to the end of file if it exists
'b': binary mode
't': text mode (default)
'+': open for updating (reading and writing)
#open the file with mode 'wb'
pickle_out = open("dict.pickle","wb")
You can see dict.pickle file created in current directory.
#dump the dictionary object
pickle.dump(dict1, pickle_out)
pickle_out.close()
list1 = ["a", "b", "c", "d", "e", "f"]
list1
pickle_out_list = open("list.pickle","wb")
pickle.dump(list1, pickle_out_list)
pickle_out_list.close()
def add(x, y):
return(f"Addition of {x} & {y} = {x + y}")
pass
a1 = add(2, 5)
print(a1)
pickle_out_obj1 = open("obj1.pickle","wb")
pickle.dump(a1, pickle_out_obj1)
pickle_out_obj1.close()
class Blog:
def __init__(self, id, title, author):
self.id = id
self.title = title
self.author = author
pass
def __str__(self):
s = f'Id: {self.id}\nTitle: {self.title}\nAuthor: {self.author}'
return s
pass
pass
blog = Blog(1, "How to read file in python", "Nutan")
print(blog)
pickle_out_obj2 = open("obj2.pickle","wb")
pickle.dump(blog, pickle_out_obj2)
pickle_out_obj2.close()
We have serialized dictionary, list, method and class. Let us deserialize all of them.
#open the file with mode 'rb'
dict_pickle_in = open("dict.pickle","rb")
#load the object
dict1 = pickle.load(dict_pickle_in)
print(dict1)
list_pickle_in = open("list.pickle","rb")
list1 = pickle.load(list_pickle_in)
print(list1)
obj1_pickle_in = open("obj1.pickle","rb")
a1 = pickle.load(obj1_pickle_in)
print(a1)
obj2_pickle_in = open("obj2.pickle","rb")
blog1 = pickle.load(obj2_pickle_in)
print(blog1)