ArrayList - Reading a Text File - Python Programming Exercise

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

 Copy 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

 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.

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

  •  File Search Operations

    In this exercise, you will develop a Python program that searches for a specific word or phrase within a text file. This exercise is perfect for practicing fil...

  •  Implementing a Queue Using List

    In this exercise, you will develop a Python program to implement a queue using a list. This exercise is perfect for practicing data structures, list manipulati...