Practice Question 21
In this question, we will learn how to write a function that scans a text file and calculates exactly how many blank lines it contains. This is very useful for cleaning up data or checking document formatting.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
When you press “Enter” in a text editor to leave a blank line, Python sees that line as just a \n. Here is how we count them:
-
Read Line by Line: We use
f.readlines()to get a list of all lines. -
The
strip()Technique: For every line, we use.strip(). This removes the hidden newline (\n) and any accidental spaces. -
The Length Check: After stripping, if the line is truly blank, its length will be
0. -
The Counter: Every time we find a line with a length of
0, we increment our count.
Let’s Code as per the above logic :
def countBlankLines():
f = open("paragraph.txt", "r")
linelist = f.readlines()
count = 0
for line in linelist:
# strip() removes \n and whitespace
# If the line is blank, it becomes an empty string ""
if len(line.strip()) == 0:
count += 1
f.close()
return count
# To call the function and see the result:
print("Total number of blank lines:", countBlankLines())
Important Notes for Students
As a teacher, I want you to pay close attention to these points, as they are where most students make mistakes in exams:
-
-
Why
strip()is mandatory: If a line has a single space on it, it looks blank to a human, but Python sees it aslen() == 1. Usingstrip()ensures that lines with only spaces are also counted as blank. -
readlines()Advantage: This method is perfect here because it preserves the structure of the file, allowing us to examine each line as an individual item in a list. -
Alternative Check: Instead of
len(line.strip()) == 0, you can also writeif line.strip() == "":. Both are logically identical.
-
Teacher’s Secret Tip for Exams:
If the examiner asks you to Remove blank lines instead of counting them, use the “Temporary File” logic we learned in Question 15. Only write lines to the new file if len(line.strip()) > 0.
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set
Exam Special Recommendation: If you are studying in 12th class and preparing for your board exam, then go for the “Computer Science with Python Sample Paper Book“. It contains 3 previous years’ papers and 7 practice papers solved strictly as per the CBSE pattern. Click here to purchase your copy!