How to Count the Number of File Lines in Python


Here we can get the methods to get a file name and counts the number of rows in the file with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter the name of the file with .txt extension: ")
count = 0
with open(fileName, 'r') as file:
    for line in file:
        count += 1
print("The number of lines: ", count)
Content of test1.txt: 
line1
line2
line3

Output:

Enter the name of the file with .txt extension: test1.txt
The number of lines: 3
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments