Python Program to Loop through the lines of a file to read the whole file, line by line

In the following example of a Python program that demonstrates how to loop through the lines of a file to read the whole file, line by line :
Program :
try:
    with open('example.txt', 'r') as file:
        # Loop through the lines of the file and print each one
        for line in file:
            print(line)
except FileNotFoundError as e:
    print(f"File not found: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
In this example, the `open()` function is used to open the file named "example.txt" in read-only mode, and the `with` statement is used to ensure that the file is properly closed after it has been read.

The `for` loop is used to iterate over the lines of the file one by one. Inside the loop, each line is printed to the console.

Note that the `for` loop automatically reads each line of the file until it reaches the end. This is a convenient way to read the entire file without having to worry about how many lines it contains. If you need to keep track of the line number, you can use the `enumerate()` function, like this :
Program :
try:
    with open('example.txt', 'r') as file:
        # Loop through the lines of the file and print each one with its line number
        for i, line in enumerate(file):
            print(f"Line {i+1}: {line}")
except FileNotFoundError as e:
    print(f"File not found: {e}")
except Exception as e:
    print(f"An error occurred: {e}")
In this example, the `enumerate()` function is used to generate a sequence of tuples, where the first element of each tuple is the line number (starting at 1) and the second element is the line itself.

These tuples are then unpacked into the `i` and `line` variables inside the `for` loop, and the line number and line contents are printed to the console for each iteration.