Certainly! The shelve module in Python is used for persisting Python objects to a file in a dictionary-like structure. Here's an example of how to read and save variables using the shelve module.
Example Program
Let's say we have some variables we want to save and later retrieve using shelve.
Saving Variables
import shelve
# Variables to save
name = "Alice"
age = 30
favorites = {
"color": "blue",
"food": "pizza",
"hobby": "reading"
}
# Open a shelve file to save the variables
with shelve.open('mydata') as db:
db['name'] = name
db['age'] = age
db['favorites'] = favorites
print("Variables saved successfully.")
In the above program, we:
- Import the
shelve module.
- Define some variables (
name, age, favorites).
- Open a shelve file named
mydata in write-back mode using shelve.open().
- Save the variables to the shelve file using dictionary-style assignments.
Reading Variables
import shelve
# Open the shelve file to read the variables
with shelve.open('mydata') as db:
saved_name = db['name']
saved_age = db['age']
saved_favorites = db['favorites']
# Print the retrieved values
print("Retrieved Variables:")
print(f"Name: {saved_name}")
print(f"Age: {saved_age}")
print(f"Favorites: {saved_favorites}")
In this program, we:
- Open the same shelve file
mydata in read mode using shelve.open().
- Retrieve the variables from the shelve file using dictionary-style access.
- Print the retrieved values.
Complete Example:
Here is a combined program to demonstrate saving and reading variables.
import shelve
# Variables to save
name = "Alice"
age = 30
favorites = {
"color": "blue",
"food": "pizza",
"hobby": "reading"
}
# Saving variables
with shelve.open('mydata') as db:
db['name'] = name
db['age'] = age
db['favorites'] = favorites
print("Variables saved successfully.")
# Reading variables
with shelve.open('mydata') as db:
saved_name = db['name']
saved_age = db['age']
saved_favorites = db['favorites']
# Print the retrieved values
print("\nRetrieved Variables:")
print(f"Name: {saved_name}")
print(f"Age: {saved_age}")
print(f"Favorites: {saved_favorites}")
Explanation of Output:
After running the complete example:
- The program will first save the variables into the shelve file
mydata.
- Then it will read the variables back from
mydata.
- Finally, it will print the values of the retrieved variables.
Console Output:
Variables saved successfully.
Retrieved Variables:
Name: Alice
Age: 30
Favorites: {'color': 'blue', 'food': 'pizza', 'hobby': 'reading'}
The above output indicates that the variables were successfully saved to and retrieved from the shelve file using the shelve module.