python shelve模块_Python中shelve模块的简单介绍(附示例)

本篇文章给大家带来的内容是关于Python中shelve模块的简单介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

shelve:对象持久化的保存的模块,将对象保存到文件里 (默认的数据存储文件为二进制),可持久化任何pickle可支持的Python数据格式

shelve 中唯一的方法:

shelve.open(filename,flag = 'c', protocol = None , writebake = False)filename关联的文件路径

flag'r' :以只读模式打开一个已经存在的数据存储文件

'w' :以读写模式打开一个已经存在的数据存储文件

'c' :(默认)以读写模式打开一个数据存储文件,如果不存在则创建

'n' :总是以读写模式打开并且创建一个新的空数据存储文件

protocol表示序列化数据所使用的协议,默认为 None(pickle v3)

writebake表示是否开启回写功能

1. 文件可以像字典一样存储key - value (注:key 必须为字符串,value 可以是任何数据类型)import shelve

date = shelve.open('family.txt') # Python的自处理系统会自动生成三个文件

date['father'] = 'Presly' # 默认为创建并且写入“c”

date['mather'] = 'Vera'

date['baby'] = [123, ]

date.close()

m = shelve.open('family.txt', falg= 'r', writebake=True) # 当writebake设置为True时,文件里才能直接添加

print(m['baby'])

m['baby'].append(345)

print(m['father'])

print('-------------')

for key, value in m.items(): # 以字典的格式

print(key, ':', value)

m.close()[123]

Presly

-------------

father : Presly

mather : Vera

baby : [123,345]

2.shelve 的序列化可以把类的数据序列化,然后再 反序列化出元素

与pickle不同的是,pickle只能按照dump顺序,load出元素,而shelve可以直接重复拿出不同或者相同存进文件的key值,

3.shelve 可以进行类似于库,增,删,改,查import shelve

def store_information(database):

info = {}

ID = input('Enter the ID number:')

info['name'] = input('Enter the name:') # 将name ,age , phone 存入字典info里

info['age'] = input('Enter the age:')

info['phone'] = input('Enter the phone:')

database[ID] = info # 用ID : info 存入 database文件

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]) # 通过输入的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) # 当if函数结束,自动跳转到cmd = enter_command()行

elif cmd == 'lookup':

lookup_information(database)

elif cmd == '?':

print_help()

elif cmd == 'quit':

return # 跳出while循环

finally:

database.close()

if __name__ == '__main__': main()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值