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.
Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:
import numpy as np
# Save
dictionary = {‘hello’:’world’}
np.save(‘my_file.npy’, dictionary)
# Load
read_dictionary = np.load(‘my_file.npy’,allow_pickle=’TRUE’).item()
print(read_dictionary[‘hello’]) # displays “world”
FYI: NPY file viewer