Exercise
Arraylist - Reading A Text File
Objective
Develop a Python program that uses an ArrayList-like structure (a list) to read and store the contents of a text file. The program should open a specified text file, read its contents line by line, and store each line in the list. After reading the file, the program should display the contents of the list. Ensure that the program handles file reading errors, such as missing files or incorrect file paths
Example Python Exercise
Show Python Code
def read_file_to_list(file_path):
"""Reads a text file and stores its contents line by line in a list."""
lines = [] # List to store file lines
try:
with open(file_path, 'r') as file:
# Read each line from the file and append to the list
for line in file:
lines.append(line.strip()) # Remove leading/trailing whitespace from each line
return lines
except FileNotFoundError:
# Handle the case where the file does not exist
print(f"Error: The file '{file_path}' was not found.")
except IOError as e:
# Handle other IO errors (e.g., permission issues)
print(f"Error reading the file '{file_path}': {e}")
return None
def display_lines_from_list(lines):
"""Displays the contents of the list."""
if lines:
print("Contents of the file:")
for line in lines:
print(line)
else:
print("No data to display.")
def main():
"""Main function to run the program."""
file_path = input("Enter the path of the text file to read: ").strip() # Prompt user for file path
# Read the file and store its contents in a list
lines = read_file_to_list(file_path)
# Display the lines if the file was successfully read
display_lines_from_list(lines)
# Run the program
if __name__ == "__main__":
main()
Output
Enter the path of the text file to read: example.txt
Contents of the file:
This is the first line.
This is the second line.
This is the third line.
Share this Python Exercise