by BehindJava

Write a program to Count the Number of Words in a Text File in Python

Home » python » Write a program to Count the Number of Words in a Text File in Python

In this tutorial we are going to learn about counting the Number of Words in a Text File in Python

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

fname = input("Enter file name: ")
 
num_words = 0
 
with open(fname, 'r') as f:
    for line in f:
        words = line.split()
        num_words += len(words)
print("Number of words:")
print(num_words)

Explanation

  1. User must enter a file name.
  2. The file is opened using the open() function in the read mode.
  3. A for loop is used to read through each line in the file.
  4. Each line is split into a list of words using split().
  5. The number of words in each line is counted using len() and the count variable is incremented.
  6. The number of words in the file is printed.