Iterate File Lines
Demonstrate safe iteration over lines in a file with a context manager.
BeginnerTopic: File Handling Programs
Python Iterate File Lines Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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 ...
Understanding Iterate File Lines
Shows the canonical pattern 'with open(...) as f' and enumeration of lines.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.