Shelve module in python not working: “db type cannot be determined”

不打扰是莪最后的温柔 提交于 2019-12-05 07:04:02

I think you're misunderstanding how the shelve module works. It opens a database file. When you try and open an existing file that contains a Python script, it's trying to detect what database type the file contains (since shelve supports multiple backend databases).

I think instead you want something like this:

import os
import shelve

curdir = os.path.dirname(__file__)
passwords = shelve.open(os.path.join(curdir, 'password_db'))

This will create a new file in the same directory as your script called password_db.<db> where <db> is an implementation-specific database file extension.

I've experienced this issue as well. It seems to be related to undocumented conditions for the filename argument of shelve.open. It is currently very intransparent (e.g. shelve.open("/tmp/tmphTTQLda") works while shelve.open("/tmp/tmphTTQLd") doesn't). Failure and success of variable filenames are hard to predict. I requested an explanation in form a documentation enhancement at http://bugs.python.org/issue23174.

In my case opening a persistent dict outside shelve and passing it to shelve.Shelve works, e.g. code

a = dumbdbm.open(tempfile.mkstemp()[1])
b = shelve.Shelf(dict=a)

and do with b what you'd have done with the return value of shelve.open.

Arnold Roa

There is one bug with anydb https://bugs.python.org/issue13007 that could not use the right identification for gdbm files.

So if you are trying to open a valid gdbm file with shelve and is thorwing that error use this instead:

    mod = __import__("gdbm")
    file = shelve.Shelf(mod.open(filename, flag))

More information on this question: shelve db type could not be determined, whichdb is not recognizing gdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!