Python doesn’t need a library for this. To count words in a file in Python, read the file into a string, call split() with no arguments, and take len() of the list. Every run of spaces, tabs and newlines counts as one break:
with open("reviews.txt", encoding="utf-8") as f:
word_count = len(f.read().split())
Below I’ll use a small file of US customer reviews, plus a few strings, so you can compare methods on the same text. All output comes from Python 3.12.5 on Windows.
Count words in a text file with split()
Here’s the sample file, reviews.txt. It has punctuation, a price, a date, a contraction and one blank line, which is enough to show where the methods disagree:
Great blender, worth every penny at $49.99. It's quiet and fast!
Shipping to Denver took 3 days -- the box arrived on May 4, 2026.
Great price, great service. I'd buy it again; the greatest deal this year.
This script reports lines, words and characters, much like the Linux wc command:
with open("reviews.txt", encoding="utf-8") as f:
text = f.read()
words = text.split()
lines = text.splitlines()
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {len(text)}")
print(f"First five words: {words[:5]}")
Output:
Lines: 4
Words: 38
Characters: 207
First five words: ['Great', 'blender,', 'worth', 'every', 'penny']

Notice that split() keeps punctuation attached, so blender, counts as one word. The blank line counts as a line but adds no words. If you’re new to reading files, see reading a file as a string in Python.
Count words in a large file line by line
f.read() loads the entire file into memory. For huge logs or exports, loop over the file object instead; it yields one line at a time:
def count_words(path):
with open(path, encoding="utf-8") as f:
return sum(len(line.split()) for line in f)
# build a bigger test file: 250,000 copies of a 10-word order note
with open("orders.txt", "w", encoding="utf-8") as f:
for i in range(250_000):
f.write(f"Order {i} shipped to Austin, TX for $19.99 on 2026-03-14\n")
print(f"orders.txt: {count_words('orders.txt'):,} words")
print(f"reviews.txt: {count_words('reviews.txt'):,} words")
Output:
orders.txt: 2,500,000 words
reviews.txt: 38 words
The generator inside sum() keeps only one line in memory, so the same function handles a tiny file and a 250,000-line file. Reading a file line by line in Python covers more ways to loop over lines.
Count words in a string with split()
Once the text is in a variable, counting words in a string works the same way. The no-argument form is the one you want, because it ignores leading, trailing and repeated whitespace:
sentence = "Count the words in this sentence"
messy = " New York\tis\nbusy "
print(len(sentence.split()))
print(len(messy.split())) # tabs, newlines and extra spaces are fine
print(len("".split())) # an empty string has 0 words
print(len(messy.split(" "))) # split(" ") counts empty pieces too
Output:
6
4
0
6
The last line is the classic mistake. split(" ") splits on each single space, so the padding at both ends adds empty pieces while York is
busy stays glued together.
If you need the words themselves, splitting a sentence into a list of words goes further, and counting characters in a string covers letters rather than words.
How do I ignore punctuation when counting words?
A regular expression lets you decide what a word is. re.findall() returns every match, so len() of the result is the count. I ran three rules on the same file:
import re
with open("reviews.txt", encoding="utf-8") as f:
text = f.read()
print("split(): ", len(text.split()))
print(r"\w+ pattern: ", len(re.findall(r"\w+", text)))
print("letters + ' only:", len(re.findall(r"[A-Za-z]+(?:'[A-Za-z]+)?", text)))
print(re.findall(r"\w+", "It's $49.99"))
Output:
split(): 38
\w+ pattern: 40
letters + ' only: 33
['It', 's', '49', '99']

\w+ counts digits as words and splits contractions at the apostrophe. The letters-only pattern skips the numbers and keeps It's whole, which matches how most people count words in prose.
Pick one rule and stick with it. The syntax is explained in regular expressions in Python.
Count word frequency in a file with Counter
To see how often each word appears, feed the word list to collections.Counter. Lowercasing first makes Great and great the same word:
import re
from collections import Counter
with open("reviews.txt", encoding="utf-8") as f:
words = re.findall(r"[a-z]+(?:'[a-z]+)?", f.read().lower())
counts = Counter(words)
print(f"Total words: {sum(counts.values())}, unique: {len(counts)}")
for word, n in counts.most_common(4):
print(f"{word:<8}{n}")
Output:
Total words: 33, unique: 30
great 3
the 2
blender 1
worth 1

most_common(n) returns the n highest counts, already sorted. For more on this class, see the Counter class in Python.
Count a specific word in a file
For one word, it’s tempting to call text.count("great"). That counts substrings, though, so it also matches inside longer words like greatest:
import re
with open("reviews.txt", encoding="utf-8") as f:
text = f.read().lower()
print(text.count("great")) # substring: also hits "greatest"
print(re.findall(r"[a-z]+", text).count("great")) # whole words only
print(len(re.findall(r"\bgreat\b", text))) # same result with a regex
Output:
4
3
3
Counting in the word list, or with a \b word-boundary regex, gives the whole-word answer. The string method is covered in the Python string count() method, and checking if a word is in a string helps when you only need yes or no.
Count words in every text file in a folder
With pathlib, glob("*.txt") finds the files and read_text() opens and closes each one. This script creates three notes, then totals them:
from pathlib import Path
folder = Path("notes")
folder.mkdir(exist_ok=True)
(folder / "monday.txt").write_text("Call the Chicago office about the Q3 budget.", encoding="utf-8")
(folder / "tuesday.txt").write_text("Send invoices to Seattle and Boston clients today.", encoding="utf-8")
(folder / "wednesday.txt").write_text("Team lunch at noon.", encoding="utf-8")
total = 0
for path in sorted(folder.glob("*.txt")):
n = len(path.read_text(encoding="utf-8").split())
total += n
print(f"{path.name:<15}{n:>3} words")
print(f"{'Total':<15}{total:>3} words")
Output:
monday.txt 8 words
tuesday.txt 8 words
wednesday.txt 4 words
Total 20 words

Use rglob("*.txt") to include subfolders. Listing files in a directory with Python shows other ways to find the files.
Python word count methods compared
| Method | Best for | Punctuation | Memory |
|---|---|---|---|
len(f.read().split()) | Quick total for normal files | Stays attached | Whole file |
sum(len(line.split()) for line in f) | Large files | Stays attached | One line |
len(re.findall(pattern, text)) | Your own word rule | You decide | Whole file |
Counter(words) | Word frequency | Depends on the word list | One entry per unique word |
These guides pair well with word counting:
- Read a specific line from a text file in Python
- Remove specific words from a string in Python
- Count numbers in a string in Python
- Write a list to a file in Python
Frequently asked questions
How do I count the words in a text file in Python?
Open the file, read it, and use len(text.split()). For big files, sum len(line.split()) over each line.
How do I count words in a string in Python?
Use len(s.split()). The no-argument split() ignores extra spaces, tabs and newlines.
Why is my word count higher than expected?
You probably used split(" "), which counts empty strings between repeated spaces. Use split() with no arguments.
How do I count words without punctuation?
Use a regex such as re.findall(r"[A-Za-z]+(?:'[A-Za-z]+)?", text) and take the length of the result.
How do I find the most common words in a file?
Lowercase the words, pass them to collections.Counter, and call most_common(n).