我需要将大约十二个对象保存到文件中,然后再恢复它们。我试图使用带有泡菜和搁置的for循环,但它无法正常工作。
编辑。 我试图保存的所有对象都在同一个类中(我之前应该已经提到过),我没有意识到我可以像这样保存整个类:
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'
如果需要保存多个对象,可以简单地将它们放在单个列表或元组中,例如:
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
)。
二进制模式也应该与Python 3一起使用,因为它的默认协议产生二进制(即非文本)数据(写入模式'wb'
和读取模式'rb'
)。
您可以使用klepto
,它为内存,磁盘或数据库提供持久性缓存。
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db['1'] = 1
>>> db['max'] = max
>>> squared = lambda x: x**2
>>> db['squared'] = squared
>>> def add(x,y):
... return x+y
...
>>> db['add'] = add
>>> class Foo(object):
... y = 1
... def bar(self, x):
... return self.y + x
...
>>> db['Foo'] = Foo
>>> f = Foo()
>>> db['f'] = f
>>> db.dump()
>>>
然后,解释器重启后......
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db
file_archive('foo.txt', {}, cached=True)
>>> db.load()
>>> db
file_archive('foo.txt', {'1': 1, 'add': <function add at 0x10610a0c8>, 'f': <__main__.Foo object at 0x10510ced0>, 'max': <built-in function max>, 'Foo': <class '__main__.Foo'>, 'squared': <function <lambda> at 0x10610a1b8>}, cached=True)
>>> db['add'](2,3)
5
>>> db['squared'](3)
9
>>> db['f'].bar(4)
5
>>>
以下方法看似简单,可以与不同大小的变量一起使用:
import hickle as hkl
# write variables to filename [a,b,c can be of any size]
hkl.dump([a,b,c], filename)
# load variables from filename
a,b,c = hkl.load(filename)