sort text file in python

How to Sort Text File in Python

Python is a powerful programming language that allows you to work with a wide range of files, including text files. Sometimes you may need to sort text file in python as a part of larger application or process. In this article, we will look at how to sort text file in python.


How to Sort Text File in Python

Let us assume you have a text file /home/ubuntu/data.txt.

Hello World
A beautiful day
Where are you
Good Morning

In the above file, we want to sort each sentence based on alphabetical order.

So we will read all lines of the file, using readlines() function which returns each line as a string in a list. One we have the list, we simply call sort function to sort them. Here is the code (sort_data.py) to sort the text file.

FileName = ("/home/ubuntu/data.txt")
data=file(FileName).readlines()
data.sort()
for i in range(len(data)):
    print data[i]

Here is the output of above code.

A beautiful day
Good Morning
Hello World
Where are you

Just run the above code as shown to sort your text file.

$ sudo python sort_data.py

In this short article, we have learnt how to sort lines of a text file.

Also read:

How to Check UFW Log & Status
How to Create Symbolic Link in Linux
Ubuntu Change Terminal Font Color & Size
How to Remove Sticky Bit in Linux
How to Truncate File in Linux

Leave a Reply

Your email address will not be published.