0

I have been working to learn the pickle and dbm python modules. I wrote some code that connected to a dbm database and wrote data and pickled info.

import dbm
import pickle
class PickleDB:
    def set_dbname(self):
        self.db = dbm.open("pickle", "n")
    def get_data(self):
        self.raw_data = input("Enter your raw data")
        self.pickled_data = pickle.dumps(self.raw_data)
    def write_to_db(self):
        self.db["Raw"] = self.raw_data
        self.db["Pickled"] = self.pickled_data
pickled_db = PickleDB()
pickled_db.set_dbname()
pickled_db.get_data()
pickled_db.write_to_db()

Everything works fine while running the program, but problems arise when I try to access the database. The keys aren't available.

>>> db = dbm.open("pickle", "n")
>>> db["Raw"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Raw'
>>>  db.keys()
[]

Why is this? Why is the data not written to the database?

Bobby Tables
  • 1,154
  • 4
  • 15
  • 25
  • 1
    This has *nothing* to do with pickle (pickling is not involved in the "Raw" key); reduce it to a minimal test-case with appropriate title (for you, as this is a lesson in debugging, and so it will be useful to others later). I am closing as "Too Localized" for the issues mentioned above. –  May 09 '12 at 21:55
  • You might need to close `db` explicitly before your program exits. See the example in [the docs](http://docs.python.org/py3k/library/dbm). – Thomas K May 10 '12 at 11:50

1 Answers1

0

The issue is that you wipe out your db when you open it up with the option 'n'. From pydoc dbm:

'n' always creates a new database.

You might want to take a look at the shelve package. If I understand what you are trying to do right, "shelve" already does it for you.

Yves Dorfsman
  • 2,684
  • 3
  • 20
  • 28