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