内容简介:如果我们只需要存少量的数据,一个简单的存储方案是使用shelve模版。我们只需要给他提供一个指定路径的文件名。shelve调用过程是,先调用open函数,参数为文件名。返回值是一个shell对象。这个对象可以用来存储数据,可以作为一个字典来操作,但是键一定是字符串类型的。操作完成后调用close函数。看下shelve的简单使用,第一段代码中,d不见了,因为当用shell对象查找元素时,这个对象根据已经存储的版本进行构建,当给某个键时,被存储了。
如果我们只需要存少量的数据,一个简单的存储方案是使用shelve模版。我们只需要给他提供一个指定路径的文件名。shelve调用过程是,
先调用open函数,参数为文件名。返回值是一个 shell 对象。这个对象可以用来存储数据,可以作为一个字典来操作,但是键一定是字符串类型的。操作完成后调用close函数。看下shelve的简单使用,
import shelve
#参数为文件名,会在当前运行目录下创建三个文件
#test.dat.bak
#test.dat.dat
#test.dat.dir
s=shelve.open('test.dat')
s['x'] = ['a','b','c']
s['x'].append('d')
print(s['x'])
输出
['a', 'b', 'c']
temp=s['x']
temp.append('d')
s['x']=temp
print(s['x'])
输出
['a', 'b', 'c', 'd']
第一段代码中,d不见了,因为当用shell对象查找元素时,这个对象根据已经存储的版本进行构建,当给某个键时,被存储了。
上述过程如下,
['a','b','c']赋值给x键;
d添加时,当前版本并未保存;
获取值时,获取的是原始版本,因此d不见了。
而第二段,temp是副本,副本修改后,重新保存了,所以能获取到d。我们再通过这个例子,看看shelve实现简单的数据存储。
如下,使用shelve模版模拟简单数据库的使用。
import sys,shelve
def store_person(db):
"""
Query user for data store it in the shelf object
"""
pid=input("输入唯一编码:")
person={}
person['name'] =input('请输入姓名:')
person['age']=input('请输入年龄:')
person['phone']=input('请输入电话号码:')
db[pid]= person
def lookup_person(db):
"""
Query user for id and desired field,and fetch the corresponding data form the shelf object
"""
pid = input('输入唯一编码:')
field=input('以下信息请输入:(name,age,phone)')
field=field.strip().lower()
print(field.capitalize()+':',\
db[pid][field])
def print_help():
print('有效的命令有:')
print('store: 保存一个person对象')
print('lookup: 通过id查询一个person对象')
print('quit: 保存退出')
print('?:显示帮助信息')
def endter_command():
cmd=input('输入命令:(按?请求帮助)')
cmd=cmd.strip().lower()
return cmd
def main():
#此处路径根据实际的文件路径更改,不用提前创建该文件,会自动创建
#D:\\work\\Python\\是我本地电脑存在的目录,大家测试可以自行修改目录
database= shelve.open('D:\\work\\Python\\database.dat')
try:
while True:
cmd=endter_command()
if cmd=='store':
store_person(database)
elif cmd=='lookup':
lookup_person(database)
elif cmd=='?':
print_help()
elif cmd =='quit':
return
finally:
database.close()
#调用
main()
操作输出如下
输入命令:(按?请求帮助)? 有效的命令有: store: 保存一个person对象 lookup: 通过id查询一个person对象 quit: 保存退出 ?:显示帮助信息 输入命令:(按?请求帮助)store 输入唯一编码:1 请输入姓名:yangyoushan 请输入年龄:31 请输入电话号码:13011111 输入命令:(按?请求帮助)lookup 输入唯一编码:1 以下信息请输入:(name,age,phone)name Name: yangyoushan 输入命令:(按?请求帮助)quit
功能文件下载: https://download.csdn.net/download/yysyangyangyangshan/10860069
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 少说话多写代码之Python学习056——标准模块(自定义模块)
- 少说话多写代码之Python学习061——标准模块(time模块)
- 少说话多写代码之Python学习062——标准模块(random模块)
- 少说话多写代码之Python学习065——标准模块(re模块)
- 少说话多写代码之Python学习057——标准模块(看看一些系统模块)
- 少说话多写代码之Python学习021——导入模块
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Automate This
Christopher Steiner / Portfolio / 2013-8-9 / USD 25.95
"The rousing story of the last gasp of human agency and how today's best and brightest minds are endeavoring to put an end to it." It used to be that to diagnose an illness, interpret legal docume......一起来看看 《Automate This》 这本书的介绍吧!