HomePythonPython Program to Count the Number of Blank Spaces in a Text File

Python Program to Count the Number of Blank Spaces in a Text File

Text files often contain various characters, including blank spaces. This python program demonstrates how to create a Python program that reads a text file and counts the number of blank spaces present in its contents.

Problem Statement

Write a Python program that takes the name of a text file as input, reads its contents, and counts the occurrences of blank spaces within the text.

Python Program to Count the Number of Blank Spaces in a Text File

def count_blank_spaces(filename):
    try:
        with open(filename, 'r') as file:
            contents = file.read()
            blank_space_count = contents.count(' ')
            return blank_space_count
    except FileNotFoundError:
        return 0

# Input
file_name = input("Enter the name of the text file: ")

# Counting blank spaces in the file
blank_space_count = count_blank_spaces(file_name)

# Output
print("Number of blank spaces in the file:", blank_space_count)

Input / Output

Python Program to Count the Number of Blank Spaces in a Text File

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...