Editor

Python Program to Count Words in a Text File

Beginner · File handling · CBSE class 12 practical list

This program counts the words in a text file, line by line and in total. A word here is any group of characters separated by spaces, so "apps," with its comma still counts as one word. It is a basic CBSE class 12 file handling program.

Program

count_words_in_file.py
# Make a sample file to work on (in your practical file, this file already exists)
with open("story.txt", "w") as f:
f.write("Python is a popular language.\n")
f.write("It is used for web apps, data science and games.\n")
f.write("\n")
f.write("Students love it!\n")
total = 0
line_number = 0
with open("story.txt", "r") as f:
for line in f:
line_number += 1
words = line.split() # splits on any run of spaces, tabs or newlines
print("Line", line_number, "has", len(words), "words")
total += len(words)
print("Total words in the file:", total)
Output
Line 1 has 5 words
Line 2 has 10 words
Line 3 has 0 words
Line 4 has 3 words
Total words in the file: 18

How it works

  1. The sample file has an empty line and extra spaces on purpose, to show that they do not confuse the count.
  2. line.split() with no argument splits on any amount of whitespace, so three spaces in a row still separate just two words, and an empty line gives an empty list.
  3. len(words) is the number of words on that line, which is printed and added to total.
  4. Using split(" ") instead would be a mistake: it creates empty strings between repeated spaces and counts them as words.

Another way to write it

Reading the whole file at once

Reading the whole file at once
# Make a sample file to work on (in your practical file, this file already exists)
with open("story.txt", "w") as f:
f.write("Python is a popular language.\nStudents love it!\n")
with open("story.txt", "r") as f:
words = f.read().split()
print("Number of words:", len(words))
print("Words:", words)
Output
Number of words: 8
Words: ['Python', 'is', 'a', 'popular', 'language.', 'Students', 'love', 'it!']

f.read() returns the whole file as one string, so a single split() gives every word in the file. That is fine for small files; the line by line version uses less memory on very big ones.

Try it yourself

Change the program to also count the lines and the characters in the file.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises