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实现高效求解素数代码实例

素数是编程中经常需要用到的。 作为学习Python的示例,下面是一个高效求解一个范围内的素数的程序,不需要使用除法或者求模运算。 #coding:utf-8 #设置python...

Python使用cookielib模块操作cookie的实例教程

Python使用cookielib模块操作cookie的实例教程

cookielib是一个自动处理cookies的模块,如果我们在使用爬虫等技术的时候需要保存cookie,那么cookielib会让你事半功倍!他最常见的搭档模块就是python下的ur...

在Python中处理时间之clock()方法的使用

 clock()方法返回当前的处理器时间,以秒表示Unix上一个浮点数。精度取决于具有相同名称的C函数,但在任何情况下,这是使用于基准Python或定时的算法函数。 在Wind...

python多线程并发及测试框架案例

这篇文章主要介绍了python多线程并发及测试框架案例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1、循环创建多个线程,并通过循环...

Python多维/嵌套字典数据无限遍历的实现

最近拾回Django学习,实例练习中遇到了对多维字典类型数据的遍历操作问题,Google查询没有相关资料…毕竟是新手,到自己动手时发现并非想象中简单,颇有两次曲折才最终实现效果,将过程记...