Python – Count Number of Words in Text File

Python – Count Number of Words

You can count number of words in a text file in Python by following a sequence of steps which we shall discuss in this tutorial.

In this tutorial, we shall learn how to count number of words in text file, using Python example programs.

Steps to Count Number of Words in Text File

To count the number of words in a text file, follow these steps.

  1. Open the file in read mode and handle it in text mode.
  2. Read the text using read() function.
  3. Split the text using space separator. We assume that words in a sentence are separated by a space character.
  4. The length of the split list should equal the number of words in the text file.
  5. You can refine the count by cleaning the string prior to splitting or validating the words after splitting.

Examples

1. Count number of words in given text file

In this Python Example, we will read a text file and count the number of words in it. Consider the following text file.

Text File

Welcome to pythonexamples.org. Here, you will find python programs for all general use cases.

Python Program

file = open("C:\data.txt", "rt")
data = file.read()
words = data.split()

print('Number of words in text file :', len(words))
Copy

Output

Number of words in text file : 14

2. Count number of words in Text File, where the file has multiple lines

In this Python Example, we will read a text file with multiple lines and count the number of words in it. Consider the following text file.

New line character separates lines in a text file. New line is a white space character and when we split the whole data in text file using split() method, all the words in all the sentences are split and returned as a single list.

Text File – data.txt

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.
This is another line with some words.

Python Program

file = open("C:\data.txt", "rt")
data = file.read()
words = data.split()

print('Number of words in text file :', len(words))
Copy

Output

Number of words in text file : 21

Summary

In this tutorial of Python Examples, we learned how to count number of words in a Text File, with the help of example programs.

Related Tutorials

Code copied to clipboard successfully 👍