How to Count Number of Line from Text File in Python

In this tutorial, we will learn how to program "How to Count the Number of Lines in a Text File using Python." We will explore how to count all the lines in a text file. The objective is to safely and accurately count the total number of lines from a text file. A sample program will be provided to demonstrate the coding process.

This topic is very easy to understand. Just follow the instructions I provide, and you'll be able to do it yourself with ease. The program I’ll show you demonstrates the proper way to count the total number of lines in a text file. I’ll also provide a simple and efficient method to achieve this. So, let's start coding!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. ret = False
  2.  
  3. while True:
  4.         print("\n================= Count Number of Line from Text File =================\n\n")
  5.  
  6.  
  7.  
  8.         file = open("sample.txt", "r")
  9.         counter = 0
  10.  
  11.         file_text = file.read()
  12.         listing = file_text.split("\n")
  13.  
  14.         for i in listing:
  15.                 if i:
  16.                         counter += 1
  17.  
  18.         print("The number of line in the Text File is: ", counter)
  19.  
  20.  
  21.         opt = input("\nDo you want to try again?(yes/no): ")
  22.  
  23.         if opt.lower() == 'yes':
  24.                 ret=False
  25.         elif opt.lower() == 'no':
  26.                 ret=True
  27.                 print("Exiting program....")
  28.  
  29.         else:
  30.                 print("Please enter yes/no:")
  31.                 break
  32.  
  33.         if ret == False:
  34.                 continue

This script counts the number of non-empty lines in a text file. It opens a file named sample.txt, reads its contents, and splits the text by line breaks (\n). Then, it iterates through each line, incrementing a counter for every non-empty line. After processing the file, it prints the total count of lines. The program runs in a loop, giving the user the option to try again or exit.

Output:

There you have it we successfully created How to Count Number of Line from Text File in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment