Andromeda
Note

shelve Module (Python)

Definition

A module that allows you to save Python variables (lists, dictionaries, etc.) to binary “shelf” files on the hard drive.

Why It Matters

The shelve module is the ‘persistent memory’ for small Python projects; it provides a simple, dictionary-like way to save complex data structures between runs without the overhead of a full database.

Core Concepts

  • Dictionary Interface: You interact with a shelf object exactly like a dictionary (shelf['key'] = value).
  • Persistence: Unlike standard variables, data in a shelf persists after the program terminates.
  • The Lifecycle: import shelve; s = shelve.open('mydata'); s['cats'] = ['Zophie', 'Pooka']; s.close().
  • Methods: Shelf objects have .keys() and .values() methods, just like dictionaries.
import shelve

# Saving data to a shelf file
shelf_file = shelve.open('mydata')
cats = ['Zophie', 'Pooka', 'Fat-tail']
shelf_file['cats'] = cats
shelf_file.close()

# Retrieving data later
shelf_file = shelve.open('mydata')
print(shelf_file['cats'])
shelf_file.close()

Connected Concepts