Count Words in Text File in Python

Last Updated : 12 Jan, 2026

Given a text file, count the total number of words in it. This is a common task in text processing, data analysis and file handling.

Example:

Input: Python is easy and powerful.
Output: 5

Sample Text File: (file.txt)

Capture

Below are the several different methods to perform this task:

Using read() and split()

This method reads the entire file content into memory and splits it into words. It is simple and fast for small to moderately large files.

Python
count = 0
with open('file.txt', 'r') as f:
    data = f.read()
    words = data.split()
    count += len(words)

print("Total Words:" ,count)

Output:

Total Words: 7

Explanation: 

  • open('file.txt', 'r'): Opens the file in read-only mode.
  • f.read(): Reads the entire file content into a string.
  • data.split(): Splits the string into words based on spaces.
  • len(words): Counts the total words.

Count Words While Ignoring Numbers

In this method, we count only the non-numeric words in a text file. The file is read, split into individual words, and each word is checked to see if it is numeric.

Input File: (sample_file.txt)

Welcome to GeeksforGeeks.
Hello 5 geeks.
Hello World!

Python
c = 0
with open(r'sample_file.txt','r') as file:

    data = file.read()
    lines = data.split()

    for word in lines:

        if not word.isnumeric():          
            c += 1
print(c)

Output:

Total Words: 7

Explanation:

  • data.split(): Splits the content into individual words.
  • if not word.isnumeric(): Checks if the word is not numeric.
  • c += 1: Increments the counter for non-numeric words.

Count Words Line by Line

In this method, the file is read line by line, each line is split into words, and the total count is updated. This is memory-efficient for large files.

Python
count = 0
with open('file.txt', 'r') as f:
    for line in f:
        words = line.split()
        count += len(words)

print("Total Words:", count)

Output:

Total Words: 7

Explanation:

  • count = 0: Initializes a counter to store the total number of words.
  • words = line.split(): Splits the current line into a list of words using whitespace.
  • count += len(words): Adds the number of words in the current line to the total count.

Using readlines()

readlines() loads all lines into a list. Less memory-efficient than line-by-line reading for large files but simpler to implement.

Python
count = 0

with open('file.txt', 'r') as f:
    lines = f.readlines()
    for line in lines:
        count += len(line.split())

print("Total Words:" count)

Output:

Total Words: 7

Explanation: count += len(line.split()): Splits the line into words and adds the number of words to the total count.

Comment