Shelve
The shelve
module allows us to store Python objects in a file using a dictionary-like interface. It automatically serializes objects so that we can save most Python data types, including lists and dictionaries, in a file. The data is persistent, meaning it stays available across program runs. When using shelve.open()
, we specify the name of the binary file in which the data will be stored (binary files are more efficient than text files). The main benefits of shelve
are its simplicity and automatic persistence, so objects can be easily saved, retrieved, and updated.
import shelve
with shelve.open("mydata") as db:
db["name"] = "Alice"
db["age"] = 30
with shelve.open("mydata") as db:
print(db["name"])
print(db["age"])