In Python the concept of a shelf exists—a persistent place to store an item that we may need to read in later. The "shelve" module is like a database in this way.
With shelve, we can use a dictionary as a persistent store of data. We open the shelf file by specifying a file name, and using the with-statement provides the clearest syntax.
This Python program uses the shelve module to first write entries, and then read them back in. Usually a program will only write values if necessary (like on its first run).
close()
call.string
as the value in the shelf dictionary—this is a common use case.get()
method, which allows us to specify a default value.string
) by calling the get()
method.import shelve file = "shelve_example_file" # Step 1: open the shelf file in a with-statement. with shelve.open(file) as s: # Step 2: store a list in the shelf. s["items"] = [1, 2, 3] # Step 3: store a string in the shelf. s["animal"] = "bird" # Step 4: open the shelf file again. with shelve.open(file) as s: # Step 5: read in the items list from the shelf and print it. items = s.get("items", None) print("Items =", items) # Step 6: read in the animal string and print it. animal = s.get("animal", "") print("Animal =", animal)Items = [1, 2, 3] Animal = bird
As seen in the screenshot, when we run a Python program that uses the shelve module, the specified file name is used in 3 separate files. These files make the shelve library more resilient.
The shelve module provides useful functionality around the pickle module. Instead of duplicating this code in every Python program we write, we can use the built-in shelve module.