Practice Question 14
In this question, we will learn how to perform a “Cut and Paste” operation on specific file lines. We will move lines containing the word “error” to a log file and ensure they are removed from the original source.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
Since we cannot easily delete a line inside a text file, we use a three-file strategy:
-
The Source (
f1): Read the originalserver.txt. -
The Log (
f2): A file to store the “error” lines. -
The Temporary File (
f3): A file to store everything that is NOT an error (the lines we want to keep). -
The Swap: After processing, we delete the original
server.txtand rename our temporary file toserver.txt. This makes it look like the lines were deleted!
Let’s Code as per the above logic :
import os
def transferErrorLines():
f1 = open("server.txt", "r")
f2 = open("error_log.txt", "w")
f3 = open("temp.txt", "w")
linelist = f1.readlines()
for line in linelist:
# Check if the word "error" exists in the line
if "error" in line.lower():
f2.write(line)
else:
# Keep the remaining lines in a temporary file
f3.write(line)
f1.close()
f2.close()
f3.close()
# Cleaning up and updating the original file
os.remove("server.txt")
os.rename("temp.txt", "server.txt")
# To call the function:
transferErrorLines()
Important Notes for Students
-
The
osModule: You mustimport osat the top of your code. Without it, theremove()andrename()functions will not work. -
Order of Closing: Always close your files (
f1.close(), etc.) before you try to remove or rename them. If a file is still “open” in Python, the operating system will block you from renaming it. -
Case Sensitivity: Using
"error" in line.lower()is a “Pro Tip.” It ensures that “Error,” “ERROR,” and “error” are all caught and transferred.
Teacher’s Secret Tip for Exams:
This “Temporary File” logic is the standard way to Update or Delete records in Data File Handling (Text or Binary). Learn this pattern well; it applies to almost every “Record Modification” question!
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!