python持久化存储之shelve
shelve类似于一个key-value数据库,可以很方便的用来保存Python的内存对象,其内部使用pickle来序列化数据。简单来说,使用者可以将一个列表、字典、或者用户自定义的类实例保存到shelve中,下次需要用的时候直接取出来,就是一个Python内存对象,不需要像传统数据库一样,先取出数据,然后用这些数据重新构造一遍所需要的对象。
示例1:
1#/usr/bin/env python
2# coding=utf-8
3# code from www.361way.com
4import shelve
5def test_shelve():
6 # open 返回一个Shelf类的实例
7 #
8 # 参数flag的取值范围:
9 # 'r':只读打开
10 # 'w':读写访问
11 # 'c':读写访问,如果不存在则创建
12 # 'n':读写访问,总是创建新的、空的数据库文件
13 #
14 # protocol:与pickle库一致
15 # 0: ascii串保存, 默认形式, 方便人读取
16 # 1: 旧式兼容性较强2进制形式
17 # 2: 支持新式类的2进制模式,Python2.3开始引入.
18 # writeback:为True时,当数据发生变化会回写,不过会导致内存开销比较大
19 d = shelve.open('shelve.db', flag='c', protocol=2, writeback=False)
20 assert isinstance(d, shelve.Shelf)
21 # 在数据库中插入一条记录
22 d['abc'] = {'name': ['a', 'b']}
23 d.sync()
24 print d['abc']
25 # writeback是False,因此对value进行修改是不起作用的
26 d['abc']['x'] = 'x'
27 print d['abc'] # 还是打印 {'name': ['a', 'b']}
28 # 当然,直接替换key的value还是起作用的
29 d['abc'] = 'xxx'
30 print d['abc']
31 # 还原abc的内容,为下面的测试代码做准备
32 d['abc'] = {'name': ['a', 'b']}
33 d.close()
34 # writeback 为 True 时,对字段内容的修改会writeback到数据库中。
35 d = shelve.open('shelve.db', writeback=True)
36 # 上面我们已经保存了abc的内容为{'name': ['a', 'b']},打印一下看看对不对
37 print d['abc']
38 # 修改abc的value的部分内容
39 d['abc']['xx'] = 'xxx'
40 print d['abc']
41 d.close()
42 # 重新打开数据库,看看abc的内容是否正确writeback
43 d = shelve.open('shelve.db')
44 print d['abc']
45 d.close()
46test_shelve()
示例2:
1# code from www.361way.com
2import shelve
3s = shelve.open('test_shelf.db')
4try:
5 s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
6finally:
7 s.close()
8s = shelve.open('test_shelf.db', writeback=True)
9try:
10 print s['key1']
11 s['key1']['new_value'] = 'this was not here before'
12 print s['key1']
13finally:
14 s.close()
15s = shelve.open('test_shelf.db')
16try:
17 print s['key1']
18finally:
19 s.close()
执行结果如下:
1$ python shelve_writeback.py
2{'int': 10, 'float': 9.5, 'string': 'Sample data'}
3{'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
4{'int': 10, 'new_value': 'this was not here before', 'float': 9.5, 'string': 'Sample data'}
update值如下:
1>>> import shelve
2>>> d = shelve.open("test_shelf.db")
3>>> x = d["key1"]
4>>> x.update({'xyz': '11111'})
5>>> print x
6{'int': 10, 'new_value': 'this was not here before', 'xyz': '11111', 'float': 9.5, 'string': 'Sample data'}
7>>> x.update({'int': 'int upate'})
8>>> print x
9{'string': 'Sample data', 'int': 'int upate', 'new_value': 'this was not here before', 'xyz': '11111', 'float': 9.5}
10>>>
示例3:
1>>> import shelve
2>>> d = shelve.open("shelve.db")
3>>> len(d)
42
5>>> d.keys()
6['dfcfall', 'thsall']
参考页面如下:shelve – Persistent storage of arbitrary Python objects
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/python-shelve/5322.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.