How do I save and restore multiple variables in python?
Solution 1:
If you need to save multiple objects, you can simply put them in a single list, or tuple, for instance:
import pickle
# obj0, obj1, obj2 are created here...
# Saving the objects:
with open('objs.pkl', 'w') as f: # Python 3: open(..., 'wb')
pickle.dump([obj0, obj1, obj2], f)
# Getting back the objects:
with open('objs.pkl') as f: # Python 3: open(..., 'rb')
obj0, obj1, obj2 = pickle.load(f)
If you have a lot of data, you can reduce the file size by passing protocol=-1
to dump()
; pickle
will then use the best available protocol instead of the default historical (and more backward-compatible) protocol. In this case, the file must be opened in binary mode (wb
and rb
, respectively).
The binary mode should also be used with Python 3, as its default protocol produces binary (i.e. non-text) data (writing mode 'wb'
and reading mode 'rb'
).
Solution 2:
There is a built-in library called pickle
. Using pickle
you can dump objects to a file and load them later.
import pickle
f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()
f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()
Solution 3:
You should look at the shelve and pickle modules. If you need to store a lot of data it may be better to use a database