Exercise
Table Collection And File Management
Objective
Develop a Python program to expand the exercise (tables + array + files) by creating three classes: Table, SetOfTables, and a test program. The SetOfTables class should contain an array of tables, as well as two methods to dump all data from the array into a binary file and restore data from the file.
Example Python Exercise
Show Python Code
import pickle
class Table:
"""Represents a table with width and height."""
def __init__(self, width, height):
"""Initialize the table with width and height."""
self.width = width
self.height = height
def show_data(self):
"""Display the dimensions of the table."""
print(f"Width: {self.width}, Height: {self.height}")
class SetOfTables:
"""Manages a collection of Table objects."""
def __init__(self):
"""Initialize an empty collection of tables."""
self.tables = []
def add_table(self, table):
"""Add a new table to the collection."""
self.tables.append(table)
def dump_to_file(self, filename):
"""
Save the collection of tables to a binary file.
:param filename: Name of the binary file.
"""
try:
with open(filename, 'wb') as file:
pickle.dump(self.tables, file)
print(f"Data successfully dumped to {filename}.")
except Exception as e:
print(f"Error while dumping data to file: {e}")
def restore_from_file(self, filename):
"""
Load the collection of tables from a binary file.
:param filename: Name of the binary file.
"""
try:
with open(filename, 'rb') as file:
self.tables = pickle.load(file)
print(f"Data successfully restored from {filename}.")
except Exception as e:
print(f"Error while restoring data from file: {e}")
def show_all_tables(self):
"""Display data for all tables in the collection."""
for i, table in enumerate(self.tables, start=1):
print(f"Table {i}:")
table.show_data()
# Test Program
if __name__ == "__main__":
import random
# Create an instance of SetOfTables
set_of_tables = SetOfTables()
# Generate and add 10 random tables
for _ in range(10):
width = random.randint(50, 200)
height = random.randint(50, 200)
set_of_tables.add_table(Table(width, height))
# Display all tables
print("Initial table data:")
set_of_tables.show_all_tables()
# Dump data to a binary file
filename = "set_of_tables.bin"
set_of_tables.dump_to_file(filename)
# Clear the current collection
set_of_tables.tables = []
# Restore data from the binary file
print("\nRestoring data from file...")
set_of_tables.restore_from_file(filename)
# Display the restored tables
print("\nRestored table data:")
set_of_tables.show_all_tables()
Output
Initial Table Data:
Initial table data:
Table 1:
Width: 120, Height: 80
Table 2:
Width: 150, Height: 90
...
After Restoring:
Restoring data from file...
Restored table data:
Table 1:
Width: 120, Height: 80
Table 2:
Width: 150, Height: 90
...
Share this Python Exercise