Practice Question 4
In this post, we will learn how to write a function that reads a file, replaces every digit with a ‘#’ symbol, and saves that modified version into a brand-new file. This is a common logic used for “Data Masking” or “Encryption” in programming.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
When we want to modify a file and save the results, the best approach is to use two files at once. Here is the step-by-step breakdown:
-
Dual File Handling: We open the source file (
secure.txt) in read mode and a destination file (system.txt) in write mode. -
Reading the Data: We read the entire content of the first file.
-
The Decision: We loop through every character. If it’s a digit, we write
#to our new file. If it’s not a digit, we write the original character. -
Permanent Storage: Unlike printing to the screen, the
f2.write()method saves the data permanently intosystem.txt.
Let’s Code as per the above logic :
def replaceDigits():
f1 = open("secure.txt", "r")
f2 = open("system.txt", "w")
data = f1.read()
for alpha in data:
if alpha.isdigit():
f2.write('#')
else:
f2.write(alpha)
f1.close()
f2.close()
# To call the function:
replaceDigits()
Important Notes for Students
As a teacher, I want you to pay close attention to these two points, as they are where most students make mistakes in exams:
-
The Write Mode (‘w’): When you open
system.txtwith"w", Python will automatically create the file if it doesn’t exist. If it already exists, it will clear the old content and write the new “masked” version. -
No
end=""needed: When usingf2.write(), you don’t need theend=""argument becausewrite()does not add a new line automatically likeprint()does. It preserves the file’s layout perfectly. -
Closing Both Files: This is very important! You opened two streams (
f1andf2), so you must close both. If you forget to closef2, your modified content might not save properly to the disk.
Teacher’s Secret Tip for Exams:
If the examiner asks you to count how many replacements were made, just add a count = 0 variable. Every time you write a #, increment the count (count += 1). At the very end of the function, you can print: "Successfully transfer X digits."
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