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的Django框架编写从Google Adsense中获得报表的应用

 我完成了更新我们在 Neutron的实时收入统计。在我花了一周的时间完成并且更新了我们的PHP脚本之后,我最终认决定开始使用Python进行抓取,这是值得我去花费我的时间和精...

可用于监控 mysql Master Slave 状态的python代码

复制代码 代码如下:import osimport sysimport MySQLdbdef getStatus(conn):    query = " S...

PyCharm专业最新版2019.1安装步骤(含激活码)

PyCharm专业最新版2019.1安装步骤(含激活码)

Pycharm是一款很好用的python开发工具,开发Python爬虫和Python web方面都很不错 这里我为大家提供了两种pycharm激活方式 分别为:2020年、2089年、...

Python socket C/S结构的聊天室应用实现

Python socket C/S结构的聊天室应用 服务端: #!/usr/bin/env python #coding:utf8 import socket,select def...

安装ElasticSearch搜索工具并配置Python驱动的方法

安装ElasticSearch搜索工具并配置Python驱动的方法

ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并...