Python 3 program to count the number of blank spaces in a file :

In this tutorial, we will learn how to find the total number of blank space in a text file. Following algorithm we are going to use in this example :

Algorithm :

1. Store the file path in a variable.
2. Create one variable to store the count of blank spaces and initialize it as ‘0’.
3. Open the file and read line one by one.
4. For each line, read words one by one.
5. For each word, read character one by one.
6. Check each character if it is space or not.
7. If the character is space, increment the count variable.
8. Finally print out the count.

Python 3 program :

file_path = "C:/new.txt"

space_count = 0

with open(file_path,'r') as f:
	   for line in f:
		   split_words = line.split()
		   for word in split_words:
			   for char in word:
					   space_count = space_count + 1

print("Total blank space found : ",space_count)

– In this example, we are reading the file in read mode using ‘open(file_path,’r’)’ method.
– Using a ‘for‘ loop, read all lines one by one. For each line, get the words using ‘.split()’ method.
– It will split the line into words.
– It may contain ‘space‘ if available.
– Now, use one more ‘for‘ loop and iterate through all words.
– For each word, use one ‘for‘ loop and iterate through each character of that word.
– Check for each character – if it is space or not using ‘.isSpace’ method.
– If it is a space, increment the counter.
– Finally , print out the counter.

Categories: python

Leave a Reply

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