I need to save about a dozen objects to a file and then restore them later. I've tried to use a for loop with pickle and shelve but it didn't work right.
Edit.
All of the objects that I was trying to save were in the same class (I should have mentioned this before), and I didn't realize that I could just save the whole class like this:
import pickle
def saveLoad(opt):
global calc
if opt == "save":
f = file(filename, 'wb')
pickle.dump(calc, f, 2)
f.close
print 'data saved'
elif opt == "load":
f = file(filename, 'rb')
calc = pickle.load(f)
else:
print 'Invalid saveLoad option'
ベストアンサー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'
).