我将数据存储在使用 python 2.7 创建的架子文件中
当我尝试从 python 3.4 访问该文件时,出现错误:
>>> import shelve
>>> population=shelve.open('shelved.shelf')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "C:\Python34\lib\shelve.py", line 223, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "C:\Python34\lib\dbm\__init__.py", line 88, in open
raise error[0]("db type could not be determined")
dbm.error: db type could not be determined
我仍然能够在 python 2.7 中毫无问题地访问架子,因此似乎存在向后兼容性问题。有没有办法用新的python版本直接访问旧的格式?
据我现在了解,这是导致我的问题的路径:
- 最初的架子是在 Windows 中使用 Python 2 创建的
- Python 2 Windows 默认使用 bsddb 作为搁置的底层数据库,因为 dbm 在 Windows 平台上不可用
- Python 3 不附带 bsddb。底层数据库是Python 3 for Windows 中的dumbdbm。
我最初考虑为 Python 3 安装第三方 bsddb 模块,但很快就变得很麻烦。然后,每当我需要在新机器上使用相同的架子文件时,这似乎都会成为一个反复出现的麻烦。所以我决定将文件从 bsddb 转换为 dumpdbm,我的 python 2 和 python 3 安装都可以读取。
我在 Python 2(包含 bsddb 和 dumbdbm 的版本)中运行了以下命令:
import shelve
import dumbdbm
def dumbdbm_shelve(filename,flag="c"):
return shelve.Shelf(dumbdbm.open(filename,flag))
out_shelf=dumbdbm_shelve("shelved.dumbdbm.shelf")
in_shelf=shelve.open("shelved.shelf")
key_list=in_shelf.keys()
for key in key_list:
out_shelf[key]=in_shelf[key]
out_shelf.close()
in_shelf.close()
到目前为止,dumbdbm.shelf 文件看起来一切正常,等待对内容进行双重检查。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)