登录  /  注册

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

不言
发布: 2018-09-25 17:15:39
原创
3150人浏览过

本篇文章给大家带来的内容是关于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()
登录后复制

以上就是Python中shelve模块的简单介绍(附示例)的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号