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
Related posts:
How to Find Index of Item in List in Python
How to Import Other Python File
How to Sort CSV File in Python
How to Print Without Newline or Space in Python
How to Split String With Multiple Delimiters in Python
How to Convert DocX to Pdf in Python
How to List All Virtual Environments in Python
How to Remove Line from File Using Python

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.