Python使用shelve模块实现简单数据存储的方法

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python编程pygal绘图实例之XY线

Python编程pygal绘图实例之XY线

安装pygal,可参阅:pip和pygal的安装实例教程 基本XY线: import pygal from math import cos """ XY线是将各个点用直线连接起来的...

在Python中用has_key()方法查找键是否存在的教程

 如果给定的键在字典可用,has_key()方法返回true,否则返回false。 语法 以下是has_key()方法的语法: dict.has_key(key) 参...

python里将list中元素依次向前移动一位

问题 定义一个int型的一维数组,包含10个元素,分别赋值为1~10, 然后将数组中的元素都向前移一个位置, 即,a[0]=a[1],a[1]=a[2],…最后一个元素的值是原来第一个元...

python版本的读写锁操作方法

本文实例讲述了python版本的读写锁操作方法。分享给大家供大家参考,具体如下: 最近要用到读写锁的机制,但是python2.7的自带库里居然木有. 网上讲读写锁的例子众多,但是原理简单...

Python实现自定义函数的5种常见形式分析

本文实例讲述了Python自定义函数的5种常见形式。分享给大家供大家参考,具体如下: Python自定义函数是以def开头,空一格之后是这个自定义函数的名称,名称后面是一对括号,括号里放...