Sort lines of file with Python is an easy way to arrange the file content in ascending order. In this article, we will focus to sort lines of file with the length of each line and sorting the lines in Alphabetical order.
Sort lines of file with line length size:
Let’s consider a text with the name sortcontent.txt which
contains some lines that we will try to sort on the basis of length of the each line.
Steps to solve the program
- Open the first file using open(“sortcontent.txt”,”r”).
- Read all the lines of the file using readlines() method
- Now compare all lines one by one and exchange place
of long length lines with small length lines to re-arrange them
in ascending order using a nested loop. - re-write all the lines of the list in ascending order.
Output: Open the sortcontent.txt file to see the output. below content will be available in the file. All lines of the file will arrange in ascending as per their length.
Sort lines of file in Alphabetical order:
Let’s consider a text file with a city name list, where names are mentioned one name in each line In the below program will sort the line of the file in alphabetical order, reads all the names from a file, and print them in alphabetical order.
When we will run above program, will get following output.
Related Articles
display words from a file that has less than 5 characters.