Python Word Count in File
split()Practice

Count words in a text file

Read the whole file, split on whitespace, print how many tokens you got.

Picture this: file to words

Read text, split, count the pieces.

read()text
→
split()words
→
len(...)count

In easy words

split() with no arguments splits on any whitespace and drops extra spaces.

Where this is used

Essay length checks, log token counts, and simple NLP preprocessing.

Run algorithm

Each step highlights the matching Python line. Program output appears only when a line that prints actually runs.

Ready
input.txt
to be or not to be
1with open("input.txt") as f:
2text = f.read()
3print(len(text.split()))
Output:

Example Program

1with open("input.txt", "r", encoding="utf-8") as f:
2text = f.read()
3print(len(text.split()))