Python使用shelve模塊實現(xiàn)簡單數(shù)據(jù)存儲的方法
更新時間:2015年05月20日 15:46:09 作者:Gavin_dinggengjia
這篇文章主要介紹了Python使用shelve模塊實現(xiàn)簡單數(shù)據(jù)存儲的方法,涉及shelve模塊實現(xiàn)數(shù)據(jù)存儲的技巧,需要的朋友可以參考下
本文實例講述了Python使用shelve模塊實現(xiàn)簡單數(shù)據(jù)存儲的方法。分享給大家供大家參考。具體分析如下:
Python的shelve模塊提供了一種簡單的數(shù)據(jù)存儲方案,以dict(字典)的形式來操作數(shù)據(jù)。
#!/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中如何將數(shù)據(jù)存儲為json格式的文件
- Python 抓取數(shù)據(jù)存儲到Redis中的操作
- Python數(shù)據(jù)存儲之 h5py詳解
- python將類似json的數(shù)據(jù)存儲到MySQL中的實例
- python3爬蟲學習之數(shù)據(jù)存儲txt的案例詳解
- 舉例簡單講解Python中的數(shù)據(jù)存儲模塊shelve的用法
- 將Python中的數(shù)據(jù)存儲到系統(tǒng)本地的簡單方法
- Python實現(xiàn)疫情地圖可視化
- python如何繪制疫情圖
- python+selenium 簡易地疫情信息自動打卡簽到功能的實現(xiàn)代碼
- Python實現(xiàn)疫情通定時自動填寫功能(附代碼)
- Python繪制全球疫情變化地圖的實例代碼
- Python爬蟲爬取全球疫情數(shù)據(jù)并存儲到mysql數(shù)據(jù)庫的步驟
相關文章
Python3.7將普通圖片(png)轉換為SVG圖片格式(網(wǎng)站logo圖標)動起來
這篇文章主要介紹了Python3.7將普通圖片(png)轉換為SVG圖片格式并且讓你的網(wǎng)站Logo(圖標)從此”動”起來,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
python 接口實現(xiàn) 供第三方調(diào)用的例子
今天小編就為大家分享一篇python 接口實現(xiàn) 供第三方調(diào)用的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
python請求域名requests.(url = 地址)報錯
本文主要介紹了python請求域名requests.(url = 地址)報錯,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

