shelve: db type could not be determined

abhimanyuaryan picture abhimanyuaryan · Jan 25, 2015 · Viewed 10.2k times · Source

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])

Answer

Alex Martelli picture Alex Martelli · Jan 25, 2015

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:-).