在实际开发中,我们会经常遇到要写入一些值待到下次启动时再次使用,这种场景通常采用写文件解决,但文件读取还需要判断是否存在以及内容检验等,比较不方便

python3中的 shelve 模块是一个简单的持久化存储工具,它提供了一个类似于字典的对象,可以将 Python 对象存储到文件中

当存储变量时:

import shelve

my_string = "Hello, World!"

with shelve.open('my_shelf') as s:
    s['my_key'] = my_string

当需要使用变量时:

import shelve

with shelve.open('my_shelf') as s:
    my_string = s.get('my_key', 'default')

print(my_string)  # 输出: "Hello, World!"

使用shelve需要注意:

  • 平台兼容性差:在不同的平台之间可能不兼容
  • 额外的内存消耗:使用 writeback=True 选项时,会在关闭时将所有修改的数据写回磁盘,这会增加内存消耗
  • 并非线程安全:并发写操作可能会导致数据损坏或竞争条件,因此在多线程或多进程环境中使用时需要小心