Python Wiki
Register
Advertisement

This is a core module in Python

Shelve is a module used to store objects in a file. It uses Pickle as a help.

Usage

Shelve is really easy to use!

import shelve
shelve = shelve.open("filename-on-disk")

Now you've got something very similar to a dictionary, although keys can only be strings. To access data use something like this:

MySpecialVariable = shelve['keyname']

Then to save it, it's just like a dict:

shelve['keyname'] = MySpecialVariable

Finally, when you are finished call the close() function:

shelve.close()

Using sync()

When you're wanting to write-back to the file in case your program is killed or crashes, you can use the sync() function. To activate it, you need to change the creator like this:

import shelve
shelve = shelve.open("filename-on-disk", writeback = True)

Then just use the sync() function when you want to save:

shelve.sync()

Simple!

Advertisement