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通过SSH登陆linux并操作的实现

用的昨天刚接触到的库,在windows下通过paramiko来登录linux系统并执行了几个命令,基本算是初试成功,后面会接着学习的。 代码: >>> import...

python 实现交换两个列表元素的位置示例

在IDLE 中验证如下: >>> numbers = [5, 6, 7] >>> i = 0 >>> numbers[i],...

python实现多线程端口扫描

一个简易的TCP端口扫描器,使用python3实现。 需求:扫描目标网站开放哪些端口号,将所有开放的端口号输出。 分析:使用socket连接,如果连接成功,认为端口开放,如果连接失败,认...

浅谈python numpy中nonzero()的用法

nonzero函数返回非零元素的目录。 返回值为元组, 两个值分别为两个维度, 包含了相应维度上非零元素的目录值。 import numpy as np A = np.mat...

在CMD命令行中运行python脚本的方法

在CMD命令行中运行python脚本的方法

网上给出了各种方法,都无碍乎先切换到Python脚本所在目录,然后输入Python脚本名称并回车,本文这里给出了更简便的方法。 方法一: 进入Python脚本所在的文件夹,shift+右...