Table Collection and File Management - Python Programming Exercise

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. This exercise is perfect for practicing object-oriented programming, file handling, and data serialization in Python. By implementing this program, you will gain hands-on experience in handling object-oriented programming, file operations, and data serialization in Python. This exercise not only reinforces your understanding of object-oriented programming but also helps you develop efficient coding practices for managing user interactions.

 Category

Object Persistence Techniques

 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

 Copy 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

 More Python Programming Exercises of Object Persistence Techniques

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.

  •  Insect Data Persistence

    In this exercise, you will develop a Python program to create a new version of the "insects" exercise, which should persist the data using some form of storage, such ...

  •  City Data Persistence

    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 ...

  •  Table, Array, and File Management

    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...