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
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
- The sample file has an empty line and extra spaces on purpose, to show that they do not confuse the count.
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.len(words)is the number of words on that line, which is printed and added tototal.- 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
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.
Related programs
- Count the Words "Me" and "My" in a Text File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Display Lines Starting with T in a Text File
- Read a File Line by Line
All Python programs · CBSE class 12 practical file · Python exercises