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.
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.
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.
Print the loaded object
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.