Bạn có thể sử dụng klepto
, cung cấp bộ nhớ đệm liên tục cho bộ nhớ, đĩa hoặc cơ sở dữ liệu.
[email protected]>$ 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()
>>>
Sau đó, sau khi thông dịch khởi động lại ...
[email protected]>$ 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
>>>
Lấy mã ở đây: https://github.com/uqfoundation
Nguồn
2014-05-21 13:46:52
Xin vui lòng gửi một mẫu mã – Yossi
Bạn nói rằng bạn đã thử một vòng lặp for. Vui lòng đăng mã đó và tại sao "nó không hoạt động đúng" (tức là, những gì đã xảy ra và những gì bạn muốn xảy ra). – Blair
Nếu bạn đang ở trên các cửa sổ, hãy đảm bảo mở các tệp ở chế độ nhị phân –