Write a Python program to sort the contents of a text file and store it in another file
Objective:
- Read lines from a text file
- Sort them alphabetically
- Save the sorted lines into a new file
Python Program:
# Open the input file in read mode with open('unsorted.txt', 'r') as input_file: lines = input_file.readlines() # Sort the lines lines.sort() # Write the sorted lines to a new file with open('sorted.txt', 'w') as output_file: output_file.writelines(lines)
Explanation:
readlines()
reads all lines from the file as a list.lines.sort()
sorts them alphabetically (default is ascending).writelines()
writes the sorted list tosorted.txt
.
Make sure the input file
unsorted.txt
exists in your current working directory.
Example
Input (unsorted.txt
):
banana apple cherry
Output (sorted.txt
):
apple banana cherry
This is a simple and effective way to alphabetically sort data stored in a text file using Python.