Python Text Processing - Sorting Lines
Many times, we need to sort the content of a file for analysis. For example, we want to get the sentences written by different students to get arranged in the alphabetical order of their names. That will involve sorting just not by the first character of the line but also all the characters starting from the left. In the below program we first read the lines from a file then print them using the sort function which is part of the standard python library.
Printing the File Content
main.py
fileName = "poem.txt" data=file(fileName).readlines() for i in range(len(data)): print(data[i])
Output
When we run the above program, we get the following output
Summer is here. Sky is bright. Birds are gone. Nests are empty. Where is Rain?
Sorting Lines in the File
Now we apply the sort function before printing the content of the file. the lines get sorted as per the first alphabet form the left.
main.py
FileName = "poem.txt"
data=file(fileName).readlines()
data.sort()
for i in range(len(data)):
print(data[i])
Output
When we run the above program, we get the following output
Birds are gone. Nests are empty. Sky is bright. Summer is here. Where is Rain?