Python Program to Count the Number of Lines in Text File

This is a Python Program to count the number of lines in a text file.

Problem Description

The program takes the file name from the user and counts number of lines in that file.

Problem Solution

1. Take the file name from the user.
2. Read each line from the file and increment the count variable
3. Print the line count.
4. Exit.

Program/Source Code

Here is source code of the Python Program to count the number of lines in a text file. The program output is also shown below.

fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f:
    for line in f:
        num_lines += 1
print("Number of lines:")
print(num_lines)
Program Explanation

1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. The line count is incremented each time and the final count is printed.

advertisement
Runtime Test Cases
 
Case 1:
Contents of file: 
Hello world
 
Output: 
Enter file name: data1.txt
Number of lines:
1
 
Case 2:
Contents of file: 
This programming language is
Python
 
Output: 
Enter file name: data2.txt
Number of lines:
2

Sanfoundry Global Education & Learning Series – 1000 Python Programs.

If you wish to look at all Python Programming examples, go to 1000 Python Programs.

👉 Join Sanfoundry classes at Telegram or Youtube

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels

advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations