Write a program to Count the Number of Blank Spaces in a Text File in Python
In this tutorial we are going to learn about couting the Number of Blank Spaces in a Text File in Python.
fname = input("Enter file name: ") k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: for letter in i: if(letter.isspace): k=k+1 print("Occurrences of blank spaces:") print(k)
- User must enter a file name.
- The file is opened using the open() function in the read mode.
- A for loop is used to read through each line in the file.
- Each line is split into a list of words using split().
- A for loop is used to traverse through the words list and another for loop is used -to traverse through the letters in the word.
- If the letter iterated over is a space, the letter count is incremented.
- The final count of occurrences of blank spaces is printed.