shelve 模块

一. 什么是 shelve 模块

  • shelve 模块也是 Python 提供给我们的序列化工具

  • shelvepickle 用起来简单一些

二、使用方法

  • 使用时, 只需要使用 open 函数获取一个 shelf 对象 (类似字典)

  • 可以将shelf对象看做一个字典来存储数据 (key 必须为字符串, 值可以是Python所支持的数据类型)

  • 然后对数据进行增删改查, 操作完成后, 将内容从内存刷到磁盘中, 最后调用 close 函数关闭文件

三、使用示例

1.保存数据

import shelve,datetimef = shelve.open(r"./b.txt")    #文件自动会创建三个文件,如果文件存在就会报错
f["user_info"] = {"name":"宋同学","age":88}
f["hobby_list"] = ["Knock_code","sleep","chicken","eat"]
f["time_now"] = datetime.datetime.now()
​
f.close()

2.获取数据(演示多种取值方法)

import shelve
f=shelve.open(f"./b.txt")
​
print(f.get("user_info"))  # {'name': '宋同学', 'age': 88}
print(f.get("hobby_list")) # ['Knock_code', 'sleep', 'chicken', 'eat']
print(f.get("time_now"))   # 2021-01-10 23:08:29.017929print(f["user_info"])      # {'name': '宋同学', 'age': 88}
print(f["hobby_list"])     # ['Knock_code', 'sleep', 'chicken', 'eat']
print(f["time_now"])       # 2021-01-10 23:08:29.017929print(f["user_info"]["name"])     # 宋同学
print(f["hobby_list"][1])         # sleep
print(f.get("user_info")["age"])  # 88
print(f.get("hobby_list")[0])     # Knock_codef.close()