Write a Python program to sort the contents of a text file and store it in another file

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:

  1. readlines() reads all lines from the file as a list.
  2. lines.sort() sorts them alphabetically (default is ascending).
  3. writelines() writes the sorted list to sorted.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.

Leave a Reply

Your email address will not be published. Required fields are marked *