Deserialization is a process in which we retrieve objects that are serialized earlier. In Python, deserialization is known as unpickling. Python's pickle
module is required to perform deserialization.
import pickle
inputFile = open('filename', 'rb')
load()
method to obtain deserialized object it. This function takes the above-created file object as an argument. Make sure you write this statement in a try
block.
pickle.load(inputFile)
inputFile.close()
Note: You will get EOFError exception when you try to read end of file. Don't forget to handle this exception.
#Python Program to deserialize object import pickle #Employee class class Employee: #Constructor def __init__(self, name, empid, salary): self.name = name self.empid = empid self.salary = salary #Opened the employee.dat file in read binary mode inputFile = open('employee.dat', 'rb') endOfFile = False #It is used to indicate end of file while not endOfFile: try: emp = pickle.load(inputFile) print("Employee Name: ", emp.name) print("Employee ID: ", emp.empid) print("Employee Salary: ", emp.salary) except EOFError: #When end of file has reached EOFError will be thrown #and we are setting endOfFile to True to end while loop endOfFile = True inputFile.close()#Close the file
Output of the above program
Employee Name: Keshav Employee ID: 1 Employee Salary: 50000 Employee Name: Madhav Employee ID: 2 Employee Salary: 55000 Employee Name: Govind Employee ID: 3 Employee Salary: 45000
#Python Program to deserialize dictionary import pickle inputFile = open('mobile.dat', 'rb') endOfFile = False #It is used to indicate end of file while not endOfFile: try: dict = pickle.load(inputFile) print("Brand Name: ", dict['brand']) print("Model: ", dict['model']) print("Phone price: ", dict['price']) except EOFError: #When end of file has reached EOFError will be thrown #and we are setting endOfFile to True to end while loop endOfFile = True inputFile.close()#Close the file
Output of the above program
Brand Name: Samsung Model: Galaxy A7 Phone price: 21990
#Python Program to deserialize list import pickle inputFile = open('programming.dat', 'rb') endOfFile = False #It is used to indicate end of file while not endOfFile: try: list = pickle.load(inputFile) for language in list: print(language) except EOFError: #When end of file has reached EOFError will be thrown #and we are setting endOfFile to True to end while loop endOfFile = True inputFile.close()#Close the file
Output of the above program
Python Numpy Pandas