Program to count number of lines in the text file using Python

Introduction

The task is to count the total number of lines in the text file.

Program to count number of lines in the text file using PythonProgram

open_file = open("demo.txt","r") 
count  = 0
text = open_file.read() 
list = text.split("\n") 
for x in list: 
    if x: 
        count += 1
  
print("Total number of lines in the text file are:", count )

Output

Program to count number of lines in the text file using Python Output

Explanation

Approach:

  • Open the text file using open() function.
  • Read the text file and split the text when “\n” is encountered and store in a list.
  • Traverse through the list and increment the count variable.
  • Return the count value that is the total number of lines in text file.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.