Python has the pickle module just for this kind of thing.
These functions are all that you need for saving and loading almost any object:
def save_obj(obj, name ):
with open('obj/'+ name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name ):
with open('obj/' + name + '.pkl', 'rb') as f:
return pickle.load(f)
These functions assume that you have an obj
folder in your current working directory, which will be used to store the objects.
Note that pickle.HIGHEST_PROTOCOL
is a binary format, which could not be always convenient, but is good for performance. Protocol 0
is a text format.
In order to save collections of Python there is the shelve module.