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 Get Current Directory in Python
How to Start Background Process in Python
How to Create Python Dictionary from String
How to Convert Unix Timestamp to Datetime in Python
How to Upgrade All Python Packages with Pip
How to Check if String Matches Regular Expression
How to List All Virtual Environments in Python
How to Read File Line by Line Into Python List

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