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
1# 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.
After this program
If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.