In this article, you are going to learn how to count the number of lines in a text file using a Python program with a simple understandable code.
In the programming language, text files are used to store data inside a file, functioning as a simple document for data sharing. When working with text files, one simple task is to count the total number of lines that the file contains. In this article, we will discuss the process of counting the number of lines in a text file using a Python program.
Counting the number of lines in a text file
Let’s suppose the text file looks like this to count the number of lines in it!
INPUT: Code Speedy is a wonderful platform to learn and find coding solutions. programming such as: PHP, WordPress, HTML, CSS, JavaScript, Python and much more.
Code
def count_lines(filename): with open(filename) as file: lines=file.readlines() Totalnum_lines= len(lines) return Totalnum_lines count=count_lines("textfile.txt") #replace with your text file name print("Total number of lines in the file:", count)
Output: Total number of lines in the file: 8
Explanation of the code
- The ‘count_lines()’ this function takes a filename as an argument.
- Second line will open the file called “file.txt” that will be an file object, the file object has a method called readlines.
- ‘Readline’ is going to return each line in the file as a list.
- ‘len’ will return the number of elements in a list.
- ‘count=count_lines’ this line calls the function; it returns the value and stores it in the count.
Steps to run the code
- Save the program file in a .py file format.
- Place the text file where you saved the python file in the same directory.
- Open a terminal and choose the open file option to choose the file you want to run.
- run the python file (e.g., Command Prompt, idle, etc.)
- The output will display the total number of lines in the specified text file.
Conclusion
In this article, you have learned the process of creating a simple python program to count the number of lines in a text file, this is the basic python program you can modify with your specifications. Thank you for learning with us. Have a great journey.