Best Practice to Save and Load Python Object From a File with Pickle – Python Tutorial

By | August 25, 2019

Python pickle libary can allow us to save any python object to a binary file, then we can load this python object from that binary file. In this tutorial, we will introduce how to use pickle to save and load python object.

python pickle examples and tutorials

Import library

import pickle

Create a python class

class Car:
  #Constructor to initialize
  def __init__(self, price,color):
      self.price = price
      self.color = color

  #function to print car price and color
  def display(self):
      print ('This car is', self.color, self.price)

We can create a python object by class Car, then save it to a binary file.

Create a python object

car_obj = Car(12345, 'red')
car_obj.display()

The display result is:

This car is red 12345

Save this object to binary file

with open("binary_car.bin","wb") as f:
    pickle.dump(car_obj, f)

If you find TypeError: file must have a ‘write’ attribute, you can read this tutorial.

Fix Python Pickle TypeError: file must have a ‘write’ attribute Error – Python Tutorial

Load this object from a binary file

with open("binary_car.bin","rb") as f:
    car_obj_2 = pickle.load(f)

If you find TypeError: file must have ‘read’ and ‘readline’ attributes, you can refer to this tutorial.

Fix Python Pickle Load TypeError: file must have ‘read’ and ‘readline’ attributes Error – Python Tutorial

Print the loaded object

print(type(car_obj_2))
car_obj_2.display()

From the print result, we can find car_obj is the same to car_obj2. Both of them are:

<class '__main__.Car'>
This car is red 12345

Then we can save a python object to a file and load it from a file successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *