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()
一个例子

例子来源于:https://blog.csdn.net/u010480899/article/details/52864518

 

猜你喜欢

转载自www.cnblogs.com/Vera-y/p/9687758.html