Python: Storing Objects Using Shelve

The shelve is used to store Python objects to a file in a dictionary like format.shelve is used where using a relational database would create too much overhead or is unnecessary for example to persist data between program runs.

Shelve is part of the Python Standard Library so getting it to work in your programs is simple, all you have to do is import the module.

import shelve
shelf = shelve.open("some-filename.db")

The above code imports the shelve module and saves it to a filename.

# Assigning data to a shelf
first_name = "John"
shelf[first_name] = first_name

# Accessing data from a shelf
student_name = shelf[firstname]
print student_name

# When you're finished, close the shelf
shelf.close()

As you can see, the shelf is accessed by keys, just like a dictionary and easy to use. Don’t forget to close your shelf file each time you open it!

Shelve does not store or track modifications to objects by default. If you would like to update the contents of an item in a shelf, you have to explicitly update the item by storing it again. Alternatively you can call the shelve constructor with writeback=True. This enables you to update the shelf easily.

More info about shelve can be found here.