Saturday, October 26, 2019

Pickle in Python

What is Pickle?
Ans:
Suppose we want to store some employee data like id, name, salary in a file. This data is well structured and got different types. to store such data, we need to create a class Employee with the instance variables id, name, salary as shown here:

Class Emp:
       def __init__(self ,id, name ,salary):
              self.id = id
              self.name = name
              self.salary = salary
   
      def display(self):
             print("{:5d} {:20s} {:10.2f}".format(self.id,self.name,self.salary))

Then we create an object to this class and store actual data into that object. This object should be stored into a binary file in the form of bytes.this is called pickle or serialization.

Pickling is done using dump() method of pickle module as

pickle.dupm(object, file)

And unpicking is done using the load() method of pickle module

object = pickle.load(file)


No comments: