Home
Python
shelve Example (shelve.open)
Updated Mar 14, 2024
Dot Net Perls
Shelve. 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.
pickle
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.
Dictionary
Example. 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).
Step 1 For using the shelve module, it is usually best to use the with-statement so we can avoid writing the close() call.
Step 2 We can store any data type that pickle supports as a value in the shelf dictionary. Here we use a list.
List
Step 3 It is possible to use a string as the value in the shelf dictionary—this is a common use case.
Step 4 To read in the data from a shelf file, we can open it inside a with-statement (a context manager).
Step 5 We can access values from the shelf dictionary by using the get() method, which allows us to specify a default value.
Step 6 For our demonstration, we access the "animal" value (a 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
Files. 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.
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 14, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen