如何将Python 3.10的shelve文件迁移至Python 3.11?
问题概述
- 代码:
with shelve.open("cache") as db: ... - Python 3.10.9运行结果:生成单个
cache.db文件 - Python 3.11.1运行结果:生成三个文件
cache.cir、cache.bak、cache.dat - 需求:升级至Python 3.11.1后,需将旧
cache.db中的数据迁移至新格式以继续使用 - 已尝试:查阅shelve官方文档及Python更新日志,未找到相关迁移说明
迁移方案
直接在Python 3.11环境中读取旧文件数据,重新写入新格式即可,具体步骤如下:
- 编写迁移脚本:
import shelve # 读取旧版shelve数据 with shelve.open("cache") as old_db: # 把所有数据转存到字典 all_data = dict(old_db) # 写入新版shelve格式 with shelve.open("cache_new") as new_db: new_db.update(all_data)
- 运行脚本后会生成
cache_new.cir、cache_new.bak、cache_new.dat三个新版文件,将它们重命名为cache.cir、cache.bak、cache.dat替换原文件即可。
如果直接用shelve.open("cache")无法读取旧文件,可尝试指定旧版使用的后端模块(比如旧版用的是dbm.gnu):
import shelve import dbm.gnu with shelve.open("cache", dbmodule=dbm.gnu) as old_db: all_data = dict(old_db)
内容的提问来源于stack exchange,提问作者user9608133
相关产品推荐
相关产品推荐

