Count total number of words in a text file using Python

In this tutorial, we will learn how to count the number of words in a text file using Python. We have generated a text file that contains a lot of words. Then our code will read the file and return us the total number of words present in our text file.

This topic belongs to the concept of file handling. Therefore, we have a clear concept of this file handling.

What is File Handling?

File handling is a very important concept in the programming language. It has many functions such as creating, reading, writing, updating and deleting. The open() function helps to open a file. After that, it returns an object as a file. This file object has read() method or write() method to read or write the content of the file. The read() method returns the text of the file and also you can mention how many characters you want to return.

Let’s do an example. We can take a text file called example.txt. In this text file, we have a sentence i.e.

I am a good boy

In this example, we have seen that there are only 5 words present in this text file. So, we can count this through the concept of file handling in Python. We have used the open() function in the text file. Therefore, we applied the read() method to get the characters present in the text file. After that, we have used the split() method to get the words separately. Then len() function can be used to count the number of words.

Count the number of words

text= open("example.txt", "rt")
print("Total words: ",len(word))


Total words:  5

For more details, you can go through this article.

Leave a Reply

Your email address will not be published. Required fields are marked *