Iterate File Lines in Python
for line in f: under with open(...). File closes even if you break or explode.
BeginnerFile Handling ProgramsExample 16 of 20
iterate-file-lines.py
Run in browser1# Program to iterate over file lines23filename = input("Enter filename: ")45try:6 with open(filename, "r", encoding="utf-8") as f:7 for line_no, line in enumerate(f, start=1):8 print(f"{line_no}: {line.strip()}")9except FileNotFoundError:10 print("File not found.")
Output
Enter filename: notes.txt 1: First line 2: Second line ...
What's going on
Shows the canonical pattern 'with open(...) as f' and enumeration of lines.