Count Lines in File in Python
Count how many lines are present in a text file.
BeginnerFile Handling ProgramsExample 13 of 20
count-lines-in-file.py
Run in browser1# Program to count lines in a file23filename = input("Enter filename: ")45try:6 with open(filename, "r", encoding="utf-8") as f:7 count = sum(1 for _ in f)8 print("Line count:", count)9except FileNotFoundError:10 print("File not found.")
Output
Enter filename: notes.txt Line count: 10
What's going on
Iterating over the file object yields one line at a time; we simply count iterations.