shelve provides persistent, dictionary-like storage for Python objects. Instead of keeping every value in memory, it stores data in a file on disk while preserving key-based access. section 13.9
Use shelve when an application needs convenient access to parts of a large collection:
- Open a shelf with shelve.open(); the address-book file is created if it does not already exist. section 13.9
- Read and write entries with dictionary syntax, but use strings for keys. section 13.9
- Close the shelf after updating it so the stored data can be reused later. section 13.9
- Access individual pieces of a large file without reading or writing the entire collection. section 13.9
A persistent address book
import shelve book = shelve.open("addresses") book['flintstone'] = ('fred', '555-1234', '1233 Bedrock Place') book['rubble'] = ('barney', '555-4321', '1235 Bedrock Place') book.close() book = shelve.open("addresses") print(book['flintstone']) # ('fred', '555-1234', '1233 Bedrock Place') section 13.9
The shelf behaves like a persistent dictionary: values entered in one Python session remain available when the same shelf is opened again. It is convenient for object storage, though database applications may benefit most when many accesses target large files. section 13.9 section 13.11
