Python: 初识shelve module

看一段开源的Python工具源码,发现采用了shelve这个module来存储数据,而且接口设计的非常好用。这里简单介绍一下。

这是python自带的一个非常实用的module,用来进行数据存储非常方便。

简单来说, 通过在当前或者指定路径建立一个文件来存储字典结构的数据: 字典的key是用字符串,value可以使任何数据对象。它与dbm不同的是,字典的值可以是 任意的数据对象。

下面我们暂从Python的官方Manuals中的例子来说明其用法:
import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level library

d[key] = data # store data at key (overwrites old data if
                # using an existing key)

data = d[key] # retrieve a COPY of data at key (raise KeyError if no
                # such key)

del d[key] # delete data stored at key (raises KeyError
                # if no such key)

flag = d.has_key(key) # true if the key exists
klist = d.keys() # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4) # this works as expected, but...
d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close() # close it



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值