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 Flatten List of Tuples in Python
How to Import Other Python File
How to Check if String Matches Regular Expression
How to Check if Key Exists in Python Dictionary
How to Delete All Instances of Character from String in Python
How to Convert Bytes to String in Python
How to Select Multiple Columns in Pandas Dataframe
How to Convert List to String in Python

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