Python Program to Count Words in Text File

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

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

Things to do Before Program

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

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

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

Count Total Words in a Text File

This is the simplest program that counts total number of words in a text file entered by 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 newly created file fresherearth.txt and press ENTER key to count and print the number of words available in this file:

count words in text file python

Modified Version of Previous Program

This program uses end, that skip insertion of an automatic newline. The try-except block is used for exception handling. That is, if file entered by user doesn't exist or anything other error gets thrown by open() method inside the try block, then program flow goes to except block and execute 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 same user input as of 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 previous program) that how to count words, refer to Count Words in String article to get every required things.

Count Words in Text File using split()

This program uses split() method to split string into a list. And the len() method counts 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 same user input as of very first program in this article:

python count total words in file

Python Online Test


« Previous Program Next Program »