Python3-shelve模块-持久化字典

Python3中的shelve提供了持久化字典对象

  和字典基本一个样,只不过数据保存在了文件中,没什么好说的,直接上代码

  注:

    1.打开文件后不要忘记关闭文件

    2.键只能是字符串,值可以是任何值

    3.shelve模块中依赖pickle模块哦(了解一下,shelve相当于对pickle又进行了一次封装)

import shelve


class Books:
    def __init__(self, name):
        self.book_name = name

# 打开持久化字典文件,没有会创建新文件,使用上下文管理器,防止忘记关闭文件
with shelve.open("dict_file") as dict_db:
    print(type(dict_db))
    # 和字典的操作一样,只不过是将数据保存到了文件中
    dict_db["name"] = "Jet"
    dict_db["age"] = 18
    dict_db["book"] = Books("追风筝的人")  # 可以保存类的信息哦!
    for k, v in dict_db.items():
        print("键: %s 值: %s" % (k, v))
View Code
原文地址:https://www.cnblogs.com/qq1207501666/p/6633042.html