Python使用shelve模塊實(shí)現(xiàn)簡單數(shù)據(jù)存儲的方法
本文實(shí)例講述了Python使用shelve模塊實(shí)現(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程序設(shè)計(jì)有所幫助。
- 詳解Python中如何將數(shù)據(jù)存儲為json格式的文件
- Python 抓取數(shù)據(jù)存儲到Redis中的操作
- Python數(shù)據(jù)存儲之 h5py詳解
- python將類似json的數(shù)據(jù)存儲到MySQL中的實(shí)例
- python3爬蟲學(xué)習(xí)之?dāng)?shù)據(jù)存儲txt的案例詳解
- 舉例簡單講解Python中的數(shù)據(jù)存儲模塊shelve的用法
- 將Python中的數(shù)據(jù)存儲到系統(tǒng)本地的簡單方法
- Python實(shí)現(xiàn)疫情地圖可視化
- python如何繪制疫情圖
- python+selenium 簡易地疫情信息自動打卡簽到功能的實(shí)現(xiàn)代碼
- Python實(shí)現(xiàn)疫情通定時(shí)自動填寫功能(附代碼)
- Python繪制全球疫情變化地圖的實(shí)例代碼
- Python爬蟲爬取全球疫情數(shù)據(jù)并存儲到mysql數(shù)據(jù)庫的步驟
相關(guān)文章
Python3.7將普通圖片(png)轉(zhuǎn)換為SVG圖片格式(網(wǎng)站logo圖標(biāo))動起來
這篇文章主要介紹了Python3.7將普通圖片(png)轉(zhuǎn)換為SVG圖片格式并且讓你的網(wǎng)站Logo(圖標(biāo))從此”動”起來,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04python 接口實(shí)現(xiàn) 供第三方調(diào)用的例子
今天小編就為大家分享一篇python 接口實(shí)現(xiàn) 供第三方調(diào)用的例子,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08python請求域名requests.(url = 地址)報(bào)錯(cuò)
本文主要介紹了python請求域名requests.(url = 地址)報(bào)錯(cuò),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02使用Python實(shí)現(xiàn)為PDF文件添加圖章
在日常工作中,我們經(jīng)常需要給PDF文檔添加一些標(biāo)識,比如公司的圖章或水印圖章,所以本文就來為大家詳細(xì)介紹一下如何使用Python實(shí)現(xiàn)為PDF文件添加圖章,需要的可以參考下2023-11-11