Table, Array, and File Management - Python Programming Exercise

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

 Category

Object Persistence Techniques

 Exercise

Table, Array, And File Management

 Objective

Develop a Python program to expand the tables + array exercise, so that it includes two new methods: dumping the array data into a binary file and restoring the 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 TableManager:
    """Manages a list of tables, including saving and restoring data."""
    def __init__(self):
        """Initialize an empty list of tables."""
        self.tables = []

    def add_table(self, table):
        """Add a new table to the list."""
        self.tables.append(table)

    def dump_to_file(self, filename):
        """
        Save the list 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 to file: {e}")

    def restore_from_file(self, filename):
        """
        Load the list 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 from file: {e}")

    def show_all_tables(self):
        """Display data for all tables."""
        for i, table in enumerate(self.tables, start=1):
            print(f"Table {i}:")
            table.show_data()


# Main Program
if __name__ == "__main__":
    import random

    # Initialize the TableManager
    manager = TableManager()

    # Create and add 10 tables with random dimensions
    for _ in range(10):
        width = random.randint(50, 200)
        height = random.randint(50, 200)
        manager.add_table(Table(width, height))

    # Display all tables
    print("Initial table data:")
    manager.show_all_tables()

    # Dump data to a binary file
    filename = "tables_data.bin"
    manager.dump_to_file(filename)

    # Clear current tables
    manager.tables = []

    # Restore data from the binary file
    print("\nRestoring data from file...")
    manager.restore_from_file(filename)

    # Display restored tables
    print("\nRestored table data:")
    manager.show_all_tables()

 Output

Initial Table Data:

Initial table data:
Table 1:
Width: 120, Height: 180
Table 2:
Width: 150, Height: 75
...

After Restoring:

Restoring data from file...

Restored table data:
Table 1:
Width: 120, Height: 180
Table 2:
Width: 150, Height: 75
...

 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.

  •  Table Collection and File Management

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

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