bobb
bobb

Reputation: 1

sorting a file by index position in python

If I wanted to sort a list by student number (small sample below but the list would be larger than this):

Which gives me:

['Stephen', ' 97654', ' DOB: Mar 5', ' 1985\n'] ['Kelly', ' 58374', ' DOB: Dec 18', ' 1986\n'] ['Brian', ' 12587', ' DOB: May 20', ' 1985\n']

How would I go about sorting the file and reordering it by student number?

Upvotes: 0

Views: 807

Answers (2)

dawg
dawg

Reputation: 103774

Use csv to read it and then sort on the second field:

import csv

with open(fn) as f:
    lines=[line for line in csv.reader(f)]
    print lines   # unsorted
    print sorted(lines, key=lambda line: int(line[1]))

First prints the file:

[['Stephen', ' 97654', ' DOB: Mar 5', ' 1985'], 
 ['Kelly', ' 58374', ' DOB: Dec 18', ' 1986'], 
 ['Brian', ' 12587', ' DOB: May 20', ' 1985']]

Then the sorted version:

[['Brian', ' 12587', ' DOB: May 20', ' 1985'], 
 ['Kelly', ' 58374', ' DOB: Dec 18', ' 1986'], 
 ['Stephen', ' 97654', ' DOB: Mar 5', ' 1985']]

Once you have the sorted version, reopen the file for writing and write out the file using csv again.

Upvotes: 3

PeCosta
PeCosta

Reputation: 537

You can save a list of list like this:

f = open('studentdb.txt')
for line in f:
    g = line.split(',')
    StudentList.append(g)

Then sort by the second element with:

StudentList.sort(key=lambda x: int(x[1]))

Upvotes: 0

Related Questions