How To Count Words In File Python

In this tutorial, we will walk through the process of counting the number of words in a file using Python programming language.

This can be useful for tasks such as text analysis, word frequency calculations or simply counting the number of words in an essay or a blog post.

By the end of this tutorial, you will be able to write and execute a Python script that counts words in a file efficiently and accurately.

Step 1: Create a sample text file

First, create a sample text file that will be used throughout this tutorial to illustrate the word-counting process. The following sample text can be used:

This is a sample text file.
It contains multiple lines of text.
Each line has a variable number of words.
Some lines may have long sentences, while others have short ones.
We will use this file to count the number of words in it using Python.

Save this content in a text file named sample.txt to be used in the Python script later.

Step 2: Write a Python function to count words in a line

Before reading the entire file, let’s break down the problem by creating a Python function that counts the number of words in a given line. Here’s the code:

The count_words_in_line function splits the input line into words using the split() function and returns the length of the resulting list. The output for the provided line would be:

Number of words in the line: 5

Step 3: Read the file line by line and count words

Now that we have a function to count words in a line, let’s write the main Python script that reads the file line by line and counts the total number of words. The following code reads the sample text file and prints the total word count:

The count_words_in_file function reads the input file line by line using a with open…as statement, and loops through each line, incrementing the total word count by the number of words in the line as returned by the count_words_in_line function. The output of this script for the sample text file will be:

Total number of words in file: 46

Full Code:


In this tutorial, you learned how to count the number of words in a file using Python. We walked through the process of creating a sample text file, writing a Python function to count words in a single line, and then reading the text file line by line to calculate the total word count.

With this basic Python script, you can now efficiently count words in any text file for further text analysis or data processing tasks.