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.- ret = False
- while True:
- print("\n================= Count Number of Line from Text File =================\n\n")
- file = open("sample.txt", "r")
- counter = 0
- file_text = file.read()
- listing = file_text.split("\n")
- for i in listing:
- if i:
- counter += 1
- print("The number of line in the Text File is: ", counter)
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- 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