Python—Shelve模块

本文详细介绍了Python中Shelve模块的使用方法,包括如何存储和读取数据,以及如何更新已存储的数据。同时,还提供了一个使用Shelve模块构建简单数据库的示例,展示了如何存储和查询个人信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Python中Shelve模块提供了基本的存储操作,Shelve中的open函数在调用的时候返回一个shelf对象,通过该对象可以存储内容,即像操作字典一样进行存储操作。当在该对象中查找元素时,对象会根据已经存储的版本进行重新构建,当给某个键赋值的时候,元素会被存储。如下:

>>> import shelve

>>> data=shelve.open('db.dat')

>>> data['x']=['1','2','3']

>>> data['x']

['1', '2', '3']

>>> data['x'].append('4')

>>> data['x']

['1', '2', '3']

>>>
open函数打开了db.dat文件,在键值’x’下存储了1,2,3元素,但是,上面的例子并没有将4存储在x中,原因在于4是添加到shelve对象的副本中,修改后的版本没有被最终保存。解决的办法:在使用shelve模块修改存储对象,将临时变量绑定到获得副本上,并且在修改后重新存储该副本。
 

>>> import shelve

>>> data=shelve.open('db.dat')

>>> data['x']=['1','2','3']

>>> data['x']

['1', '2', '3']

>>> temp=data['x']

>>> temp.append('4')

>>> data['x']=temp

>>> data['x']

['1', '2', '3', '4']

>>> data['y']=['5','6']

>>> temp=data['y']

>>> temp.append('7')

>>> data['y']=temp

>>> data['x']

['1', '2', '3', '4']

>>> data['y']

['5', '6', '7']

>>>

或者将open函数的writeback参数设置为true

>>> xx=shelve.open('test.txt',writeback=True)
>>> xx['x']=['1','2','3']
>>> xx['x']
['1', '2', '3']
>>> xx['x'].append('4')
>>> xx['x']
['1', '2', '3', '4']
>>>
案例:通过shelve构造一个“数据库”,存储姓名、年龄、电话号码等信息,代码如下:
 
# _*_ coding:utf-8 _*_
import sys
import shelve

def store_information(database):
    ID=input('Enter the ID number:')
    info={}
    info['name']=input('Enter the name:')
    info['age']=input('Enter the age:')
    info['phone']=input('Enter the phone:')
    database[ID]=info
 
def lookup_information(database):
    ID=input('Enter the ID:')
    field=input('What would you like to know?(name,age,phone)')
    field=field.strip().lower()
    print(database[ID][field])

def print_help():
    print('Please enter the help command:')
    print('store :store informatinon to database')
    print('lookup :look up information by numID')
    print('quit   :save information and quit')
    print('?      :print help command')
 
def enter_command():
    cmd=input('Enter command (? for help)')
    cmd=cmd.strip().lower()
    return cmd
def main():
    database=shelve.open('db.dat')
    try:
        while True:
            cmd=enter_command()
            if cmd == 'store':
                store_information(database)
            elif cmd == 'lookup':
                lookup_information(database)
            elif cmd == '?':
                print_help()
            elif cmd == 'quit':
                return
    finally:
        database.close() 

if __name__=='__main__':main()


shelve是python的自带model。

可以直接通过import shelve来引用。

shelve类似于一个存储持久化对象的持久化字典,即字典文件。

使用方法也类似于字典。


保存对象至shelve文件中:

[python] view plain copy
  1. import shelve  
  2.   
  3. wangzhe = dict(zip(['name','age'],['wangzhe',24]))  
  4. lijianguo = dict(zip(['name','age'],['lijianguo',25]))  
  5.   
  6. db = shelve.open('shelveDict')  #打开一个文件  
  7. db['wangzhe'] = wangzhe   #向文件中添加内容,添加方式与给字典添加键值对相同  
  8. db['lijianguo'] = lijianguo      
  9. db.close()   #关闭文件  

从文件中读取对象:
[python] view plain copy
  1. import shelve  
  2. db = shelve.open('shelveDict')  #打开文件  
  3. print db['wangzhe']  #向从字典中获取键的方式一样读取内容  
  4. print db['lijianguo']  #结果为{'age': 25, 'name': 'lijianguo'}  
  5. db.close()  #关闭文件  

更新文件中的数据:

[python] view plain copy
  1. import shelve  
  2. db = shelve.open('shelveDict')  #打开文件  
  3. wangzhe = db['wangzhe']     #从文件中读取之前存储的对象  
  4. wangzhe['name'] = 'wang zhe'   #直接对对象进行修改  
  5. db['wangzhe'] = wangzhe     #重新存储至字典文件对象中  
  6. print db['wangzhe']     #结果如下{'age': 24, 'name': 'wang zhe'}  
  7. db.close()   #关闭文件 
 

转载于:https://www.cnblogs.com/hhjwqh/p/8433467.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值