Practice Question 20
In this question, we will learn how to write a function that takes the text from one file and writes it into another file in complete reverse order (from the last character to the first).
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To reverse a file efficiently, we treat the entire content as one big string.
-
Read the Whole File: We use
f.read()to capture the entire content ofnote.txtinto a variable. -
The Slicing Trick
[::-1]: In Python, strings can be sliced using the format[start:stop:step]. By using a step of-1and leaving the start/stop empty, Python automatically flips the entire string. -
Write to New File: We open
reverse.txtin write mode and dump the flipped string into it.
Let’s Code as per the above logic :
def reverseFileContent():
f1 = open("note.txt", "r")
data = f1.read()
f1.close()
#Reverse the string using slicing
reversed_data = data[::-1]
#Write the reversed content to the new file
f2 = open("reverse.txt", "w")
f2.write(reversed_data)
f2.close()
print("File content has been reversed and saved to reverse.txt")
# To call the function:
reverseFileContent()
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:
-
Character Level vs. Line Level: This logic reverses every single character. If the original file said “Hi!”, the new file will say “!iH”. If the examiner specifically asks to reverse the order of lines instead, you would use
readlines()and thenreversed(linelist). -
Memory Usage: This method loads the entire file into memory. For very large files, this might be slow, but for Class 12 and College level exams, this is the most elegant and high-scoring solution.
-
The
[::-1]Syntax: Always explain this in your Viva! The first colon represents the start, the second represents the end, and-1is the step that tells Python to go backwards.
Teacher’s Secret Tip for Exams:
If the examiner asks you to reverse each word individually but keep the words in the same order, you would first split() the data into a list, reverse each word in a loop, and then join() them back together.
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!