Python program to read file word by word (original) (raw)

Last Updated : 16 Jan, 2026

Given a text file, read it word by word and process or display each word individually.

**Example: (Myfile.txt)

read-word-by-word-python

**Output:
Geeks
4
geeks

Using split()

This method reads the file line by line and uses split() to break each line into individual words, making it a simple and efficient way to process words.

Python `

with open("Myfile.txt", "r") as f: for line in f:
for w in line.split():
print(w)

`

**Output

Geeks
4
Geeks

**Explanation:

Using a Generator Function

This method yields one word at a time while reading the file, making it memory-efficient and ideal for processing large files.

Python `

def words(fname): with open(fname, "r") as f: for line in f:
for w in line.split():
yield w

for w in words("Myfile.txt"): print(w)

`

**Output

Geeks
4
Geeks

Naive Manual Character-by-Character Approach

This method processes the file one character at a time without using Python’s built-in helpers, giving full control over how words and characters are counted.

Python `

with open("Myfile.txt", "r") as f: w = "" for ch in f.read():
if ch == " " or ch == "\n": if w: print(w) w = ""
else: w += ch
if w: print(w)

`