Exercise
Insect Data Persistence
Objective
Develop a Python program to create a new version of the "insects" exercise, which should persist the data using some form of storage, such as a database or file system.
Example Python Exercise
Show Python Code
import pickle
class Insect:
"""Represents an insect with a name and number of legs."""
def __init__(self, name, legs):
"""Initialize the insect with a name and number of legs."""
self.name = name
self.legs = legs
def show_data(self):
"""Display the insect's data."""
print(f"Name: {self.name}, Legs: {self.legs}")
class InsectManager:
"""Manages a collection of insects and handles persistence."""
def __init__(self, filename):
"""Initialize the manager with a file for persistence."""
self.filename = filename
self.insects = []
def add_insect(self, insect):
"""Add a new insect to the collection."""
self.insects.append(insect)
def show_all_insects(self):
"""Display all insects in the collection."""
if not self.insects:
print("No insects available.")
else:
for i, insect in enumerate(self.insects, start=1):
print(f"Insect {i}:")
insect.show_data()
def save_to_file(self):
"""Persist the collection of insects to a file."""
try:
with open(self.filename, 'wb') as file:
pickle.dump(self.insects, file)
print(f"Data successfully saved to {self.filename}.")
except Exception as e:
print(f"Error while saving data: {e}")
def load_from_file(self):
"""Load the collection of insects from a file."""
try:
with open(self.filename, 'rb') as file:
self.insects = pickle.load(file)
print(f"Data successfully loaded from {self.filename}.")
except FileNotFoundError:
print(f"No data file found. Starting with an empty collection.")
except Exception as e:
print(f"Error while loading data: {e}")
# Test Program
if __name__ == "__main__":
# File to persist insect data
data_file = "insects_data.bin"
# Create an instance of the InsectManager
manager = InsectManager(data_file)
# Load existing data from the file
print("Loading data from file...")
manager.load_from_file()
# Add new insects
print("\nAdding new insects...")
manager.add_insect(Insect("Ant", 6))
manager.add_insect(Insect("Spider", 8))
manager.add_insect(Insect("Centipede", 100))
# Display all insects
print("\nCurrent insects in collection:")
manager.show_all_insects()
# Save data to the file
print("\nSaving data to file...")
manager.save_to_file()
# Clear the current collection
print("\nClearing current collection...")
manager.insects = []
# Display after clearing
print("\nInsects after clearing:")
manager.show_all_insects()
# Reload data from the file
print("\nReloading data from file...")
manager.load_from_file()
# Display reloaded data
print("\nInsects after reloading:")
manager.show_all_insects()
Output
Saving data to file...
Clearing current collection...
Insects after clearing:
No insects available.
Reloading data from file...
Insects after reloading:
Insect 1:
Name: Ant, Legs: 6
Insect 2:
Name: Spider, Legs: 8
Insect 3:
Name: Centipede, Legs: 100
Share this Python Exercise
Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.
In this exercise, you will develop a Python program to create a new version of the "cities database", using persistence to store its data instead of text files. This ...
In this exercise, you will develop a Python program to expand the tables + array exercise, so that it includes two new methods: dumping the array data into a binary f...
In this exercise, you will develop a Python program to expand the exercise (tables + array + files) by creating three classes: Table, SetOfTables, and a test program....