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:
What Is __name__ In Python
How to Install Python Package with .WHL file
Python Script to Run SQL Query
How to Remove HTML Tags from CSV File in Python
How to Import from Another Folder in Python
Python Script to Load Data in MySQL
How to Randomly Select Item from List in Python
How to Execute Shell Command from Python

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