Given a text file, read it word by word and process or display each word individually.
Example: (Myfile.txt)

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.
with open("Myfile.txt", "r") as f:
for line in f:
for w in line.split():
print(w)
Output
Geeks
4
Geeks
Explanation:
- for line in f: iterates over each line in the file
- line.split(): splits the line into words using whitespace
- for w in line.split(): loop over each word
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.
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.
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)
Output
Geeks
4
Geeks