Sometimes, we want to save an object to disk with Python.
In this article, we’ll look at how to save an object to disk with Python.
How to save an object to disk with Python?
To save an object to disk with Python, we can use the pickle
module.
For instance, we write:
import pickle
class Company(object):
def __init__(self, name, value):
self.name = name
self.value = value
company = Company('foo', 'bar')
def save_object(obj, filename):
with open(filename, 'wb') as outp:
pickle.dump(obj, outp, pickle.HIGHEST_PROTOCOL)
save_object(company, 'company.pkl')
We have the Company
class that we instantiated and assigned to company
.
Then we define the save_object
function that opens filename
and call pickle.dump
with obj
, the outp
file and pickle.HIGHEST_PROTOCOL
to always save the file with the latest data.
Conclusion
To save an object to disk with Python, we can use the pickle
module.