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

yipeiwu_com6年前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中的time模块与datetime模块用法总结

time模块 time模块是包含各方面对时间操作的函数. 尽管这些常常有效但不是所有方法在任意平台中有效. time用struct_time表示时间 import time # t...

让python在hadoop上跑起来

让python在hadoop上跑起来

本文实例讲解的是一般的hadoop入门程序“WordCount”,就是首先写一个map程序用来将输入的字符串分割成单个的单词,然后reduce这些单个的单词,相同的单词就对其进行计数,不...

【Python】Python的urllib模块、urllib2模块批量进行网页下载文件

【Python】Python的urllib模块、urllib2模块批量进行网页下载文件

由于需要从某个网页上下载一些PDF文件,但是需要下载的PDF文件有几百个,所以不可能用人工点击来下载。正好Python有相关的模块,所以写了个程序来进行PDF文件的下载,顺便熟悉了Pyt...

用python一行代码得到数组中某个元素的个数方法

想法由来 今天写代码过程中遇到一个需求,计算一个list中数值为1的元素的个数,其中这个list的元素数值不是为0就是为1。 一开始想到的是写个方法来计算: # 返回一个0,1数组中...

Django 模型类(models.py)的定义详解

Django 模型类(models.py)的定义详解

一. #在models.py中添加 #代码如下 from django.db import models #出版商 class Publisher(models.Model):...