Python Program to Count Words in a Text File

This article was created to cover some programs in Python that count the total number of words available in a given text file by the user at run-time. Here is a list of programs covered in this article:

Since the program created below is based on a text file, we must do some tasks (creating the file with some contents) before proceeding with the program. Let's do this first.

Things to Do Before the Program

As directed above, we must create a text file (in the current directory) before executing the program given below. So create a file named "codescracker.txt" with the following content:

Hello World
This is a text File
My name is codescracker.txt

Save this file to the folder where the source code of the Python program to count all the words in this file is saved. Now let's move on to the program.

Count the Total Words in a Text File

This is the simplest program that counts the total number of words in a text file entered by the user. Later on, we've modified this program:

print("Enter the Name of File: ")
fileName = input()
fileHandle = open(fileName, "r")
countWord = 0
for content in fileHandle:
  chk = 0
  contentLen = len(content)
  for i in range(contentLen):
    if content[i]==' ':
      if chk!=0:
        countWord = countWord+1
      chk = 0
    else:
      chk = chk+1
  if chk!=0:
    countWord = countWord+1
print("\nTotal Word(s): ")
print(countWord)

Here is its sample run:

python count words in text file

Now enter the name of the newly created file, "codescracker.txt," and press the ENTER key to count and print the number of words available in this file:

count words in text file python

Modified Version of the Previous Program

This program uses "end", which skips the insertion of an automatic newline. The "try-except" block is used for exception handling. That is, if the file entered by the user doesn't exist or anything else gets thrown by the "open()" method inside the "try" block, then the program flow goes to the "except" block and executes the code inside that block.

print(end="Enter the Name of File: ")
fileName = input()
try:
  fileHandle = open(fileName, "r")
  countWord = 0
  for content in fileHandle:
    chk = 0
    contentLen = len(content)
    for i in range(contentLen):
      if content[i]==' ':
        if chk!=0:
          countWord = countWord+1
        chk = 0
      else:
        chk = chk+1
    if chk!=0:
      countWord = countWord+1
  if countWord>1:
    print("\nThere are " +str(countWord)+ " Words available in the File")
  elif countWord==1:
    print("\nThere is only 1 word available in the File")
  else:
    print("\nThe File is empty!")
except IOError:
  print("\nError Occurred!")
  print("The File doesn't Exist")

Here is its sample run with the same user input as the previous program:

count number of words in file python

Here is another sample run with user input, say "temp.txt" (a non-existing file):

python count number of words in file

Note: To learn more about the user-based code (as given in the previous program) for how to count words, refer to the Count Words in String article to get all the required things.

Count words in a text file using split()

This program uses the "split()" method to split a string into a list. And the "len()" method counts the total elements available in a list.

print(end="Enter the Name of File: ")
fileName = input()
try:
  fileHandle = open(fileName, "r")
  countWord = 0
  for content in fileHandle:
    wrd = content.split()
    countWord = countWord+len(wrd)
  print("\nTotal Word(s) = " + str(countWord))
except IOError:
  print("\nFile doesn't Exist!")

Here is its sample run with the same user input as the very first program in this article:

python count total words in file

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!