shelve模块
来源:互联网 发布:摩托车车架号网络查询 编辑:程序博客网 时间:2024/06/11 15:33
shelve:
是一种简单的数据存储方案,他有一个有趣的函数就是open(),这个函数接收一个参数就是文件名,会返回一个shelf对象,你可以用他来存储内容,可以简单的把它当作一个字典,当你存储完毕的时候,调用它的close方法来关闭。
简单的使用shelve模块的数据库应用程序:
import sys, shelvedef store_person(db): """ Query user for data and store it in the shelf object """ pid = raw_input('Enter unique ID number:') person = {} person['name'] = raw_input('Enter name: ') person['age'] = raw_input('Enter age: ') person['phone'] = raw_input('Enter phone number: ') db[pid] = persondef lookup_person(db): """ Query user for ID and desired filed.and fetch the corresponding data from the shelf object """ pid = raw_input('Enter ID number: ') field = raw_input('What would you like to know?(name,age,phone)') field = field.strip().lower() print field.capitalize() + ':', db[pid][field]def print_help(): print 'The available commands are:' print 'store : Stores information about a person' print 'lookup : Looks up a person from ID number' print 'quit : Save changes and exit' print '? : Prints this message'def enter_command(): cmd = raw_input('Enter command (? for help): ') cmd = cmd.strip().lower() return cmddef main(): database = shelve.open('F:\\database.dat') try: while(True): cmd = enter_command() if cmd == 'store': store_person(database) elif cmd == 'lookup': lookup_person(database) elif cmd == '?': print_help() elif cmd == 'quit': return finally: database.close()if __name__ == '__main__': main()
代码中使用了try/finally来确保数据库能够正确关闭,在一些值进行读取之后,对读取的内容调用strip和lower函数,可以让用户随意输入大小写。
运行结果:
注意:
shelve是一个对象持久化保存方法,将对象保存到文件里面,一般来说对象的保存和恢复都是通过shelve来进行的。
千万不要自己创建.dat文件,如果自己创建的话,会提示 "db type could not be determined"
解决方法: 删除database.dat文件,首次运行后会自动生成该文件。
1 0
- shelve模块
- shelve模块
- Python模块之shelve
- python模块:shelve
- Python-shelve模块
- Python——Shelve模块
- python shelve模块的用法
- shelve
- shelve
- 模拟随机访问文件:shelve模块
- Python笔记(7)shelve模块
- Python的shelve模块小问题
- python小模块--anydbm,shelve模块
- 每日一发Python---Python中shelve模块用法
- Python利用shelve模块设计简单数据库程序
- Python3.5——内置模块详解之shelve模块、xml模块、configparser模块、hashlib、hmac模块
- python3 基础模块(数据库文件模块dbm、shelve、pickle,django,mysql,ORM框架——SQLAlchemy)
- python中的shelve模块,可以提供一些简单的数据操作
- visual studio 无可用源 解决办法
- eaccelerator+PHP5.4导致smarty更新模板500报错
- poj--1080 Human Gene Functions(dp)
- iOS 使用可缩放图像的自定义按钮
- 字符串按照字典序排序
- shelve模块
- 第10,11周 项目2(1)
- 304. Range Sum Query 2D - Immutable
- 剑指offer04--根据前序和中序构建二叉树
- Cocos2d-x中的坐标转换
- Fragment和Activity
- 关于获取手机Ram总内存的方法
- Leetcode Everyday: 88. Merge Sorted Array
- linux 重定向