Serialization is a process in which an object is converted into a stream of bytes and then saved to a file. In Python, serialization is known as pickling. In order to perform serialization, you need to use built-in pickle
module.
pickle
module.
import pickle
outputFile = open('filename', 'wb')
pickle
's dump()
method and pass object as a first argument and the above-created file object as a second argument.
pickle.dump(object, outputFile)
close()
function.
outputFile.close()
Note: You can serialize any Python data structure such as dictionaries, tuples, lists, integer numbers, strings, sets, and floating-point numbers.
#Python Program to serialize 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 write binary mode outputFile = open('employee.dat', 'wb') e1 = Employee('Keshav', 1, 50000)#e1 is an Employee class object e2 = Employee('Madhav', 2, 55000)#e2 is an Employee class object e3 = Employee('Govind', 3, 45000)#e3 is an Employee class object pickle.dump(e1, outputFile)#Calling dump() function to serialize e1 object pickle.dump(e2, outputFile)#Calling dump() function to serialize e2 object pickle.dump(e3, outputFile)#Calling dump() function to serialize e3 object outputFile.close()#Close the file
When you run the above code, you will get employee.dat file. The content of this file is
#Python Program to serialize dictionary import pickle dict = {'brand': 'Samsung', 'model': 'Galaxy A7', 'price': 21990} outputFile = open('mobile.dat', 'wb') pickle.dump(dict, outputFile) outputFile.close()
When you run the above code, you will get mobile.dat file. The content of this file is
#Python Program to serialize list import pickle list = ['Python', 'Numpy', 'Pandas'] outputFile = open('programming.dat', 'wb') pickle.dump(list, outputFile) outputFile.close()
On running the above code, you will obtain programming.dat file. The content of this file is