shevlevs 自动地将pickle进和pickle出键访问文件系统。shevlevs就像一个存储持久化对象的持久化字典。
- 作为字典一样存储:
write eg
import shelve
a ='abcdefg'
b = range(1,8,1)
c = dict(zip(a,b))
d = shelve.open('cc_shelve') #实例化一个对象
d['data'] =c #通过字典的方式,添加对象的数据
d.close()
read eg
import shelve
d = shelve.open('cc_shelve')
for k,v in d['data'].items():
print(k,v)
print(d['data']['a'])
运行结果:
a 1
b 2
c 3
d 4
e 5
f 6
g 7
1
2.存储实例化类:
eg
import shelve
class Person():
def __init__(self,name,age,work):
self.name= name
self.age =age
self.work =work
def eat(self):
print(self.name,'eating.....')
def run(self):
print(self.name,'running....')
db = shelve.open('db')
wang = Person('wang',23,'computer')
li = Person('li',34,'医生')
for obj in (wang,li):
db[obj.name] = obj
读取存储文件
eg
import shelve
db = shelve.open('db')
print(list(db.keys()))
print(db['li'])
print(db['li'].eat())
print(db['li'].work)
db.close()
运行结果:
['wang', 'li']
<example_shevle.Person object at 0x0000022AAFB55FC8>
li eating.....
None
医生
改变类文件内容:
eg
class Person():
def __init__(self,name,age,work):
self.name= name
self.age =age
self.work =work
def __getattr__(self, item):
if item =='eat':
print(self.name,'eating..now...')
else:
raise AttributeError()
# def eat(self):
# print(self.name,'eating.....')
def run(self):
print(self.name,'running....')
print(db['li'].eat)
运行结果:
li eating..now...
从中可以知道,shelve库可以用来存储数据,通过更改类文件可以实现数据的展示,而不必去更改数据源本身
同时shevle 数据格式的字典键,不能以纯数字,可以使用str(int) .如: db[str(3)] 做为数据存储的键。
3.shelve 修改操作:
obj = db[key] #取回
obj.attr = value #修改
db[key] = obj #改写
网友评论