Practice Question 30
In this question, we will write a function that acts as a “Text Purifier.” It reads details.txt and removes every line that contains even a single numeric digit (0-9), saving the “clean” text-only lines into final.txt.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
We need to verify if a line is “safe” to keep. Here is the step-by-step logic:
-
Open Files: Open the source file for reading and the destination file for writing.
-
Line-by-Line Scan: Use
readlines()to look at each line individually. -
The “Flag” Logic: For each line, we assume it is “clean” (
found_digit = False). -
Nested Loop: We look at every character in the line. If a character is a digit, we flip our flag to
Trueand stop checking that line. -
Conditional Writing: If, after checking all characters, the flag is still
False, it means the line is safe to write tofinal.txt.
Let’s Code as per the above logic :
def removeNumericLines():
f1 = open("details.txt", "r")
f2 = open("final.txt", "w")
linelist = f1.readlines()
for line in linelist:
found_digit = False
# Check every character in the current line
for alpha in line:
if alpha.isdigit():
found_digit = True
break # No need to check other characters in this line
# If no digit was found, write the line to the new file
if found_digit == False:
f2.write(line)
f1.close()
f2.close()
print("Cleanup complete! Numeric lines removed and saved to final.txt")
# To call the function:
removeNumericLines()
Important Notes for Students
As a teacher, I want you to focus on these three key points so you don’t lose marks:
-
Flag Variable: The
found_digitvariable is crucial. It helps the program “remember” if it saw a number anywhere in the line while it was looping through the characters. -
breakfor Efficiency: As soon as we find one digit (like in “Room 404”), we know the line has to go. Thebreaksaves time by skipping the rest of the characters in that line. -
Preserving Formatting: Unlike
.split(), usingreadlines()andwrite(line)preserves the original spacing and newlines of the “clean” lines.
Teacher’s Secret Tip for Exams:
This logic is the foundation for all “Filtering” tasks. If the examiner asks to remove lines starting with a specific character, or lines shorter than 5 characters, you just change the if condition. The “Read -> Filter -> Write” structure remains the same!
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