ArrayList Copying a Text File - Python Programming Exercise

In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to duplicate the contents of a text file. This exercise is perfect for practicing file handling, list manipulation, and error handling in Python. By implementing this program, you will gain hands-on experience in handling file operations, list manipulation, and error handling 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

Memory Management Techniques

 Exercise

Arraylist Copying A Text File

 Objective

Develop a Python program that uses an ArrayList-like structure (a list) to duplicate the contents of a text file. The program should read the content of an existing text file and then create a copy of the file with the same content. Ensure that the program handles file reading and writing efficiently, and includes error handling for scenarios like missing files or permission issues.

 Example Python Exercise

 Copy Python Code
import os

class ArrayList:
    """A class to simulate an ArrayList-like structure using a Python list."""
    
    def __init__(self):
        """Initialize the ArrayList with an empty list."""
        self.array = []  # The underlying list to store elements

    def add(self, element):
        """Adds an element to the end of the ArrayList."""
        self.array.append(element)
    
    def get(self, index):
        """Returns the element at the specified index."""
        try:
            return self.array[index]
        except IndexError:
            print(f"Error: Index {index} out of range.")
            return None
    
    def size(self):
        """Returns the number of elements in the ArrayList."""
        return len(self.array)
    
    def display(self):
        """Displays all elements in the ArrayList."""
        if self.size() == 0:
            print("The list is empty.")
        else:
            for element in self.array:
                print(element, end="")
    
    def clear(self):
        """Removes all elements from the ArrayList."""
        self.array.clear()

def read_file(file_name):
    """Reads the content of a file and stores it in an ArrayList."""
    array_list = ArrayList()
    try:
        with open(file_name, 'r') as file:
            for line in file:
                array_list.add(line)
        print(f"File '{file_name}' read successfully.")
    except FileNotFoundError:
        print(f"Error: File '{file_name}' not found.")
    except PermissionError:
        print(f"Error: Permission denied to read the file '{file_name}'.")
    except Exception as e:
        print(f"An unexpected error occurred while reading the file: {e}")
    
    return array_list

def write_file(file_name, array_list):
    """Writes the content of the ArrayList to a new file."""
    try:
        with open(file_name, 'w') as file:
            for line in array_list.array:
                file.write(line)
        print(f"File '{file_name}' written successfully.")
    except PermissionError:
        print(f"Error: Permission denied to write to the file '{file_name}'.")
    except Exception as e:
        print(f"An unexpected error occurred while writing to the file: {e}")

def main():
    """Main function to duplicate the contents of a text file."""
    source_file = input("Enter the name of the source text file to duplicate: ")
    destination_file = input("Enter the name for the destination file: ")

    # Read content from source file
    array_list = read_file(source_file)
    
    # Write content to destination file
    if array_list.size() > 0:
        write_file(destination_file, array_list)
    else:
        print("No content to write to the destination file.")

# Run the program
if __name__ == "__main__":
    main()

 Output

Enter the name of the source text file to duplicate: source.txt
Enter the name for the destination file: destination.txt
File 'source.txt' read successfully.
File 'destination.txt' written successfully.

 Share this Python Exercise

 More Python Programming Exercises of Memory Management 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.

  •  Calculating an Unlimited Sum

    In this exercise, you will develop a Python program to calculate an unlimited sum by continuously adding numbers provided by the user. This exercise is perfect...

  •  ArrayList - Reading a Text File

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to read and store the contents of a text file. This exercise...

  •  Hash Table - Implementing a Dictionary

    In this exercise, you will develop a Python program that implements a hash table using a dictionary. This exercise is perfect for practicing data structures, d...

  •  Parenthesis Matching

    In this exercise, you will develop a Python program that checks if parentheses in a given expression are properly balanced. This exercise is perfect for practi...

  •  Merging and Sorting Files

    In this exercise, you will develop a Python program that merges the contents of multiple text files into a single file and sorts the content alphabetically or numeric...

  •  ArrayList: Storing Points

    In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to store a collection of points, where each point is represented by...