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?

Useful Video Courses


Video

Python Online Training

187 Lectures 17.5 hours

Malhar Lathkar

Video

Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty

Video

Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official

Video

Python with Data Science

Best Seller

75 Lectures 13 hours

Eduonix Learning Solutions

Video

Python 3 from scratch to become a developer in demand

Best Seller

70 Lectures 8.5 hours

Lets Kode It

Video

Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

Abhilash Nelson

Advertisements