Iterate File Lines

Demonstrate safe iteration over lines in a file with a context manager.

PythonBeginner
Python
# Program to iterate over file lines

filename = input("Enter filename: ")

try:
    with open(filename, "r", encoding="utf-8") as f:
        for line_no, line in enumerate(f, start=1):
            print(f"{line_no}: {line.strip()}")
except FileNotFoundError:
    print("File not found.")

Output

Enter filename: notes.txt
1: First line
2: Second line
...

Shows the canonical pattern 'with open(...) as f' and enumeration of lines.