本文实例讲述了python使用shelve模块实现简单数据存储的方法。分享给大家供大家参考。具体分析如下:
python的shelve模块提供了一种简单的数据存储方案,以dict(字典)的形式来操作数据。
#!/usr/bin/python
import sys, shelve
def 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] = person
def lookup_person(db):
“””
query user for id and desired field,
and fetch the corresponding data
from the shelf object
“””
pid = raw_input(‘enter unique id number:’)
temp = db[pid]
field = raw_input(‘please enter name, age or phone:’)
field.strip().lower()
print field.capitalize() + ‘: ‘, temp[field]
def print_help():
print ‘the avaliable commands are:’
print ‘store :stores infomation about a person’
print ‘lookup :looks up a person form 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 cmd
def main():
database = shelve.open(‘database’)
# database stores in current directory
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()
# close database in any condition
if __name__ == ‘__main__’:
main()
希望本文所述对大家的python程序设计有所帮助。