DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

How to Count Words in a Python String or Text File

Use len(text.split()) for a whitespace-based count in a Python string, or read a text file and apply the same expression. See the limits of this method and a line-by-line option for large files.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a basic whitespace-based count, use len(text.split()). To count a text file, read it into a string and apply the same expression. This counts whitespace-separated pieces—not necessarily words according to punctuation, hyphenation, or a language’s writing rules.

Count whitespace-separated pieces in a string

Call split() without an argument, then pass the resulting list to len():

text = "Python makes this straightforward.
Here is another line."
word_count = len(text.split())
print(word_count)  # 7

With no explicit separator, Python treats runs of whitespace—including spaces and newlines—as separators. Leading and trailing whitespace do not add items, and an empty or whitespace-only string produces a count of zero. Python’s str.split() documentation describes this behavior.

Count words in a text file

Read the file as text, then split the returned string. With pathlib:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

text = Path("input.txt").read_text(encoding="utf-8")
word_count = len(text.split())
print(word_count)

Path.read_text() returns the decoded file contents as a string and closes the file after reading. The encoding must match the file; UTF-8 is shown as an explicit assumption here. See the Python Path.read_text() reference.

You can also use the built-in open() function:

with open("input.txt", encoding="utf-8") as file:
    word_count = len(file.read().split())

print(word_count)

The with statement closes the file when the block ends. Both file examples count using the same whitespace-splitting rule as the string example.

Choose the right definition of “word”

len(text.split()) is concise when a whitespace-delimited count is what you need. It does not remove punctuation or interpret linguistic word boundaries. For example, "well-known" remains one piece, and punctuation stays attached to the surrounding text. Text with no whitespace between words remains one piece as well.

Avoid text.split(" ") for this basic count. Passing a specific separator changes the behavior: repeated spaces can produce empty items, and splitting an empty string with that separator produces [""]. If your task needs rules for punctuation, contractions, hyphenation, or languages that do not use whitespace between words, define those rules and use an appropriate tokenizer or custom logic instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Count a large file incrementally

Reading an entire file at once is simple, but a very large file may require substantial memory. Process it line by line and add each line’s whitespace-based count:

word_count = 0

with open("input.txt", encoding="utf-8") as file:
    for line in file:
        word_count += len(line.split())

print(word_count)

This avoids storing the whole decoded file in one string. It does not change the definition of a counted piece: whitespace separates items, and punctuation remains attached.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.