PHP前端开发

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

百变鹏仔 3周前 (02-06) #Python
文章标签 示例

本篇文章给大家带来的内容是关于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 可以是任何数据类型)

立即学习“Python免费学习笔记(深入)”;

import shelvedate = 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 : Preslymather : Verababy : [123,345]

2.  shelve 的序列化

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

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

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

import shelvedef 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 cmddef 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()