Practice Question 19
In this question, we will write a function that reads a source file and “extracts” only the words that have an even number of characters (like “code”, “it”, or “Python”), saving them into a separate file.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To filter words by their length, we use a simple mathematical check:
-
Open Two Files: Open the source file (
words.txt) in read mode and the destination file (even.txt) in write mode. -
Read and Split: Convert the source text into a list of words using
.split(). -
The Length Check: Use
len(word)to get the count of characters. -
The Modulus Check: A number is even if it is perfectly divisible by 2. We check this using
len(word) % 2 == 0. -
Write to File: If the condition is met, write that word followed by a space into the new file.
Let’s Code as per the above logic :
def copyEvenLengthWords():
f1 = open("words.txt", "r")
f2 = open("even.txt", "w")
data = f1.read()
wordlist = data.split()
for word in wordlist:
if len(word) % 2 == 0:
f2.write(word + " ")
print("Even-length words have been copied successfully!")
f1.close()
f2.close()
# To call the function:
copyEvenLengthWords()
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:
-
The Modulus Operator (
%): This operator gives the remainder of a division. Iflength % 2is0, the number is Even. If it is1, the number is Odd. -
Adding Spaces: When writing to the new file, we use
f2.write(word + " "). If you don’t add the" ", all the words will stick together like one giant word (e.g., “codeitPython”). -
Efficiency: This approach is very clean for board exams because it clearly shows the “Input -> Process -> Output” flow.
Teacher’s Secret Tip for Exams:
f the examiner asks you to copy Odd-length words, just change the condition to if len(word) % 2 != 0: or if len(word) % 2 == 1:. The rest of the logic remains identical!
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!