How to Count the Number of Words in a Text File in Python

In this tutorial, we will learn how to program "How to Count the Number of Words in a Text File in Python." The objective is to count all the words contained in a text file. This tutorial will guide you step by step through the process of counting words from a text file. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of counting all the words in a text file. So, let’s dive into the coding process!

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.
  1. while True:
  2.     print("\n============== Count the Number of Words in a Text File ==============\n")
  3.  
  4.     fname = input("Enter file name: ")
  5.  
  6.     try:
  7.         num_words = 0
  8.         with open(fname, 'r') as f:
  9.             for line in f:
  10.                 words = line.split()
  11.                 num_words += len(words)
  12.  
  13.         print("Number of words:", num_words)
  14.  
  15.     except FileNotFoundError:
  16.         print("File not found. Please check the filename and try again.")
  17.  
  18.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  19.     if opt == 'no':
  20.         print("Exiting program...")
  21.         break
  22.     elif opt != 'yes':
  23.         print("Invalid choice. Exiting program...")
  24.         break

This Python program counts the total number of words in a text file. It prompts the user to enter a file name, then opens the file and reads it line by line. Each line is split into individual words, and the total count is accumulated. If the specified file does not exist, it displays an error message. After showing the result, the program asks whether the user wants to try again or exit.

Output:

There you have it we successfully created How to Count the Number of Words in a 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

Python Tutorials