You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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环境中读取旧文件数据,重新写入新格式即可,具体步骤如下:

  1. 编写迁移脚本:
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)
  1. 运行脚本后会生成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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 21:30:51