如何在python中保存和恢复多个变量? [英] How do I save and restore multiple variables in python?
问题描述
我需要将大约十几个对象保存到一个文件中,然后再恢复它们.我尝试将 for 循环与 pickle 和 shelve 一起使用,但效果不佳.
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'
推荐答案
如果您需要保存多个对象,您可以简单地将它们放在一个列表或元组中,例如:
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)
如果你有很多数据,你可以通过将protocol=-1
传递给dump()
来减小文件大小;pickle
然后将使用最好的可用协议而不是默认的历史(和向后兼容)协议.在这种情况下,文件必须以二进制模式打开(分别为 wb
和 rb
).
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).
二进制模式也应该与 Python 3 一起使用,因为它的默认协议产生二进制(即非文本)数据(写入模式 'wb'
和读取模式 'rb'
).
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'
).
这篇关于如何在python中保存和恢复多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!