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
1# 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.
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.