Python sort by row

Python Sorting by Line

Often, we need to sort the contents of a file for analysis. For example, we might want to sort sentences written by different students alphabetically by their names. This involves sorting the first character of a line and all characters starting from the left. In the following program, we first read lines from a file and then sort them using the sort function, which is part of the standard Python library.

Printing a File

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

When we execute 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 a File

Now, we use the sort function before printing the file contents. Lines are sorted by the first letter on the left.

FileName = ("pathpoem.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?

Leave a Reply

Your email address will not be published. Required fields are marked *