How to Count Blank Spaces in a Text File in Python


In this example we will show how to quantity blank spaces in a text file with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter the name of the file with .txt extension: ")
count = 0
with open(fileName, 'r') as file:
    lineList = file.readlines()
    for line in lineList:
        for letter in line:
            if letter == " ":
                count += 1
print("The number of SPACE is: ", count)
Content of test1.txt:
Python is an easy to learn
powerful programming language

Output:

Enter the name of the file with .txt extension: test1.txt
The number of SPACE is: 7

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments