shelve: db type could not be determined

Question:

I am using Pycharm. First of all whenever any module is imported in Pycharm. The complete import line fades out. But in case of import shelve doesn’t fade out. Also when I run the file i get following errors:

Traceback (most recent call last):
  File "/Users/abhimanyuaryan/PycharmProjects/shelve/main.py", line 13, in <module>
    s = shelve.open("file.dat")
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/shelve.py", line 239, in open
    return DbfilenameShelf(filename, flag, protocol, writeback)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/shelve.py", line 223, in __init__
    Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/dbm/__init__.py", line 88, in open
    raise error[0]("db type could not be determined")
 dbm.error: db type could not be determined

Here’s my code:

import shelve

s = shelve.open("file.dat")

s["first"] = (1182, 234, 632, 4560)
s["second"] = {"404": "file is not present", "googling": "Google to search your content"}
s[3] = ["abhilasha", "jyoti", "nirmal"]

s.sync()

print(s["first"])
print(s["second"])
print(s[3])
Asked By: abhimanyuaryan

||

Answers:

The OP explains in a comment that 'file.dat' was created by pickle — and that’s the problem! pickle doesn’t use any DB format — it uses its own! Create file.dat with shelve in the first place (i.e run shelve when file.dat doesn’t exist yet and save the stuff into it) and you’ll be fine.

OP in comment: “I still don’t get what’s the problem in this case”. Answer: the problem is that pickle does not create a file in any of the DB formats shelve can use. Use a single module for serializing and deserializing — either just pickle, or, just shelve — and it will work SO much better:-).

Answered By: Alex Martelli

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))
Answered By: Arnold Roa

You should not put the file extension.
Do as follows:
`

import shelve

s = shelve.open("file")

s["first"] = (1182, 234, 632, 4560)
s["second"] = {"404": "file is not present", "googling": "Google to search your content"}
s[3] = ["abhilasha", "jyoti", "nirmal"]

s.sync()

print(s["first"])
print(s["second"])
print(s[3])

`
It is important to note that if the shelf file was somewhere else you need to add dir name too

Answered By: Arshia Javid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.