Count Lines in File
Count how many lines are present in a text file.
BeginnerTopic: File Handling Programs
Python Count Lines in File Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to count lines in a file
filename = input("Enter filename: ")
try:
with open(filename, "r", encoding="utf-8") as f:
count = sum(1 for _ in f)
print("Line count:", count)
except FileNotFoundError:
print("File not found.")Output
Enter filename: notes.txt Line count: 10
Understanding Count Lines in File
Iterating over the file object yields one line at a time; we simply count iterations.
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.