This is a Python Program to count the number of blank spaces in a text file.
The program reads a file and counts the number of blank spaces in a text file.
1. Take the file name from the user.
2. Read each line from the file and split the line to form a list of words.
3. Use a for loop to traverse through the words in the list and another for loop to traverse through the letters in the word.
4. Check if the letter is a space and if it is, increment the variable count.
5. Print the final count of the number of spaces.
6. Exit.
Here is source code of the Python Program to count the number of blank spaces in a text file. The program output is also shown below.
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)
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. 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.
6. If the letter iterated over is a space, the letter count is incremented.
7. The final count of occurrences of blank spaces is printed.
Case 1: Contents of file: he l l o world hello Output: Enter file name: read.txt Occurrences of blank spaces: 5 Case 2: Contents of file: t e st Output: Enter file name: read2.txt Occurrences of blank spaces: 2
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Apply for Python Internship
- Check Python Books
- Apply for Programming Internship
- Practice Programming MCQs
- Check Information Technology Books