Practice Question 23
In this question, we will learn how to write a function that acts like an “Auto-Corrector.” It will read a file and ensure every word starts with a capital letter (e.g., “once upon a time” becomes “Once Upon A Time”).
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To transform text word-by-word, we follow this sequence:
-
Open Two Files: Open the source (
story.txt) for reading and a new file (newstory.txt) for writing. -
The Split Strategy: Use
.read().split()to break the entire text into a list of individual words. -
The
.capitalize()Method: This built-in Python function converts the first character of a string to uppercase and the rest to lowercase. -
Reconstructing the File: Write each transformed word into the new file, adding a space after each word so they don’t stick together.
Let’s Code as per the above logic :
def capitalizeFirstLetter():
f1 = open("story.txt", "r")
f2 = open("newstory.txt", "w")
data = f1.read()
wordlist = data.split()
for word in wordlist:
# .capitalize() turns "python" into "Python"
cap_word = word.capitalize()
f2.write(cap_word + " ")
f1.close()
f2.close()
print("Content successfully capitalized and saved to newstory.txt")
# To call the function:
capitalizeFirstLetter()
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:
-
Handling Empty Files: Always check
if len(wordlist) > 0. If you try to accesswordlist[0]on an empty file, your program will crash with anIndexError. -
Tie-Breaker: If there are two words of the same smallest length (like “is” and “to”), this logic will keep the first one it found. To get the last one, you would change
<to<=. -
Alternative (The
min()function): Python has a built-in shortcut:smallest = min(wordlist, key=len). While this is great for real-world coding, using aforloop (as shown above) is usually preferred in Board Exams to show you understand the underlying algorithm.
Teacher’s Secret Tip for Exams:
This exact same structure is used to find the Largest word. Just change smallest = wordlist[0] to largest = wordlist[0] and change the condition to if len(word) > len(largest):
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!