Given a text file, the task is to count the total number of characters, words, spaces and lines in the file.
Example: (Myfile.txt)
Hello world
This is Python
It is easy
Output:
Lines: 3
Words: 8
Characters: 30
Spaces: 5
Using Built-in Python Functions
This is the most readable and Pythonic method. It uses split(), generator expressions and basic iteration.
f1 = "Myfile.txt"
lines =words = chars = spaces = 0
with open(f1, "r") as f:
for x in f:
lines += 1
words += len(x.split())
spaces += x.count(" ")
chars += sum(1 for c in x if c not in (" ", "\n"))
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
print("Spaces:", spaces)
Output
Lines: 3
Words: 8
Characters: 30
Spaces: 5
Explanation:
- line.split(): splits line into words
- len(line.split()): number of words in the line
- line.count(" "): counts spaces
- sum(1 for c in x if c not in (" ", "\n")): counts non-space, non-newline characters.
Using OS Module + Filtering Words
This method uses os.linesep, strip() and comprehension-based counting.Â
import os
f1 = "Myfile.txt"
lines = words = chars = spaces = 0
with open(f1, "r") as f:
for x in f:
line = x.strip(os.linesep)
wl = x.split()
lines += 1
words += len(wl)
chars += sum(1 for c in line if c not in (" ", os.linesep))
spaces += sum(1 for c in line if c in (" ",))
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
print("Spaces:", spaces)
Output
Lines: 3
Words: 8
Characters: 30
Spaces: 5
Explanation:
- line.strip(os.linesep): removes newline character
- line.split(): gives list of words
- sum(1 for c in line if ...): counts characters and spaces.
Naive Manual Approach
This method manually checks every character and updates counters. It is more complex and less readable.
fname = "File1.txt"
words = lines = chars = spaces = 0
with open(fname, "r") as f:
for line in f:
lines += 1
flag = True
for ch in line:
if ch != " " and ch != "\n" and flag:
words += 1
flag = False
elif ch == " ":
spaces += 1
flag = True
if ch not in (" ", "\n"):
chars += 1
print("Lines:", lines)
print("Words:", words)
print("Characters:", chars)
print("Spaces:", spaces)
Output
Lines: 3
Words: 8
Characters: 30
Spaces: 5