Practice Question 27
In this question, we will learn how to write a function that takes a list of words from a file and rearranges them into Alphabetical Order (A to Z) before saving them into a new file.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To sort file data, we must first bring it into a Python List, as strings themselves are “immutable” (cannot be changed in place).
-
Read and Split: We read
words.txtand use.split()to create a list of words. -
The
sort()Method: We apply.sort()to our list. By default, Python sorts strings in alphabetical order (based on ASCII values). -
Write to New File: We loop through the now-sorted list and write each word into
sorted.txt.
Let’s Code as per the above logic :
def sortWords():
f1 = open("words.txt", "r")
data = f1.read()
wordlist = data.split()
f1.close()
# Step 2: Sort the list alphabetically
wordlist.sort()
# Step 3: Write sorted words into another file
f2 = open("sorted.txt", "w")
for word in wordlist:
f2.write(word + "\n") # Writing each word on a new line
f2.close()
# To call the function:
sortWords()
Important Notes for Students
As a teacher, I want you to focus on these three key points so you don’t lose marks:
-
Case Sensitivity: In Python sorting, capital letters come before lowercase letters (e.g., ‘Z’ comes before ‘a’). If you want a truly alphabetical sort regardless of case, you would use
wordlist.sort(key=str.lower). -
sort()vssorted():list.sort()modifies the original list and returns nothing.sorted(list)creates a new sorted list. For this program,list.sort()is perfectly fine. -
Newlines: I used
\nin thewrite()function so the sorted file looks organized like a dictionary. You can change this to a space" "if you want them in a single paragraph.
Teacher’s Secret Tip for Exams:
If the examiner asks you to sort in Reverse Alphabetical Order (Z to A), simply change the sort line to: wordlist.sort(reverse=True).
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