shelve类似于一个key-value数据库,可以很方便的用来保存Python的内存对象,其内部使用pickle来序列化数据。简单来说,使用者可以将一个列表、字典、或者用户自定义的类实例保存到shelve中,下次需要用的时候直接取出来,就是一个Python内存对象,不需要像传统数据库一样,先取出数据,然后用这些数据重新构造一遍所需要的对象。
示例1:
#/usr/bin/env python # coding=utf-8 # code from www.361way.com import shelve def test_shelve(): # open 返回一个Shelf类的实例 # # 参数flag的取值范围: # 'r':只读打开 # 'w':读写访问 # 'c':读写访问,如果不存在则创建 # 'n':读写访问,总是创建新的、空的数据库文件 # # protocol:与pickle库一致 # 0: ascii串保存, 默认形式, 方便人读取 # 1: 旧式兼容性较强2进制形式 # 2: 支持新式类的2进制模式,Python2.3开始引入. # writeback:为True时,当数据发生变化会回写,不过会导致内存开销比较大 d = shelve.open('shelve.db', flag='c', protocol=2, writeback=False) assert isinstance(d, shelve.Shelf) # 在数据库中插入一条记录 d['abc'] = {'name': ['a', 'b']} d.sync() print d['abc'] # writeback是False,因此对value进行修改是不起作用的 d['abc']['x'] = 'x' print d['abc'] # 还是打印 {'name': ['a', 'b']} # 当然,直接替换key的value还是起作用的 d['abc'] = 'xxx' print d['abc'] # 还原abc的内容,为下面的测试代码做准备 d['abc'] = {'name': ['a', 'b']} d.close() # writeback 为 True 时,对字段内容的修改会writeback到数据库中。 d = shelve.open('shelve.db', writeback=True) # 上面我们已经保存了abc的内容为{'name': ['a', 'b']},打印一下看看对不对 print d['abc'] # 修改abc的value的部分内容 d['abc']['xx'] = 'xxx' print d['abc'] d.close() # 重新打开数据库,看看abc的内容是否正确writeback d = shelve.open('shelve.db') print d['abc'] d.close() test_shelve()
示例2:
# code from www.361way.com import shelve s = shelve.open('test_shelf.db') try: s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' } finally: s.close() s = shelve.open('test_shelf.db', writeback=True) try: print s['key1'] s['key1']['new_value'] = 'this was not here before' print s['key1'] finally: s.close() s = shelve.open('test_shelf.db') try: print s['key1'] finally: s.close()
执行结果如下:
$ python shelve_writeback.py {'int': 10, 'float': 9.5, 'string': 'Sample data'} {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'} {'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
update值如下:
>>> import shelve >>> d = shelve.open("test_shelf.db") >>> x = d["key1"] >>> x.update({'xyz': '11111'}) >>> print x {'int': 10, 'new_value': 'this was not here before', 'xyz': '11111', 'float': 9.5, 'string': 'Sample data'} >>> x.update({'int': 'int upate'}) >>> print x {'string': 'Sample data', 'int': 'int upate', 'new_value': 'this was not here before', 'xyz': '11111', 'float': 9.5} >>>
示例3:
>>> import shelve >>> d = shelve.open("shelve.db") >>> len(d) 2 >>> d.keys() ['dfcfall', 'thsall']
参考页面如下:shelve – Persistent storage of arbitrary Python objects
《python持久化存储之shelve》有1条评论