Python - Sorting Lines


Advertisements


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

FileName = ("path\poem.txt")
data=file(FileName).readlines()
for i in range(len(data)):
   print data[i]

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.

 FileName = ("path\poem.txt")
data=file(FileName).readlines()
data.sort()
for i in range(len(data)):
    print data[i]

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?


Advertisements