VOOZH about

URL: https://www.geeksforgeeks.org/python/python-get-number-of-characters-words-spaces-and-lines-in-a-file/

⇱ Get Number of Characters, Words, Spaces and Lines in a File - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get Number of Characters, Words, Spaces and Lines in a File - Python

Last Updated : 16 Jan, 2026

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.

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. 

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.

Output

Lines: 3
Words: 8
Characters: 30
Spaces: 5

Related Articles:

Comment