Count Lines in File

Count how many lines are present in a text file.

PythonBeginner
Python
# 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

Iterating over the file object yields one line at a time; we simply count iterations.