Practice Question 15
In this question, we will learn how to write a function that takes a character from the user and removes all lines from a file that begin with that specific character.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
Just like we did in our practice problem 14, with the “error” transfer, we cannot directly “erase” a line. Instead, we “filter” the content into a new file.
-
User Input: We ask the user for a character (e.g., ‘A’).
-
Read and Filter: We read
letter.txt. If a line does NOT start with that character, we save it intotemp.txt. -
The Overwrite: We delete the old
letter.txtand renametemp.txttoletter.txt. -
Result: The lines starting with the user’s character are gone!
Let’s Code as per the above logic :
import os
def deleteLinesByCharacter(x):
f1 = open("letter.txt", "r")
f2 = open("temp.txt", "w")
linelist = f1.readlines()
for line in linelist:
# We only write the line if it does NOT start with the given character
if line[0]==x:
f2.write(line)
f1.close()
f2.close()
os.remove("letter.txt")
os.rename("temp.txt", "letter.txt")
# To call the function:
x=input("Enter character ")
deleteLinesByCharacter(x)
Important Notes for Students
Keep these exam tips in mind:
-
Why
strip()? Sometimes lines have leading spaces. Usingline.strip().startswith(char)ensures that a space doesn’t hide the character you are looking for. -
Case Sensitivity: By default, ‘a’ and ‘A’ are different. If you want to delete both, you can use:
if not line.strip().lower().startswith(char.lower()):. -
The OS Module: Don’t forget
import os! It’s the most common reason students’ code fails to run during practicals.
Teacher’s Secret Tip for Exams:
If the examiner asks you to “Modify” or “Update” a line instead of deleting it, you would still use this same logic! Instead of skipping the line in the if block, you would simply f2.write() the modified version of that line
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!