Python : Sort file by arbitrary column, where column contains time values
Question: I have a .txt file for a person, and next to each person they have two times.
This is the .txt file

    
    
     Xantippe 09:00 11:00
     Erica 10:00 12:06
     Marcia 09:30 11:45
     Elizabeth 10:15 12:10
     Angela 11:30 13:45
     Freda 12:00 14:20
     Maria 12:30 14:10
    

I am required to read the file, then get each line, read it, and sort the
whole list by the second time. Remember in the file the numbers are string
objects. So basically the time that is the earliest i.e. 11:00 Should be at
the top of the list along with their previous time and name. eg. `Xantippe
09:00 11:00` and then on another line the next one etc.

So far I have done:

    
    
    from Practise1 import timeCalc
    with open('LadiesRace.txt', 'r') as f:
      readf = f.read();
      timeX = timeCalc()
      lis = readf.split('\n')
      with open('sortByFinishTime.txt','w') as w:
        def compare(x,y):
          if x[1] > y[1]:
            return 1
          if x[1] < y[1]:
            return -1
          return 0
        #lis.sort()
        for l in lis:
          #line = l.strip()
          slist = l.split(' ')
          print slist[2]
    

The problem is that I cannot use a dictionary, only a list. I have managed to
sort the list by name in ascending order, but how do I sort with the last
time?


Answer: Firstly, you need to get your data into a usable format... So let's load it
into a list in memory - it's important to note that `dict`s do not inherently
have order, so we want to use a list.

    
    
    with open('myfile.txt') as fin:
        lines = [line.split() for line in fin]
    

This will remove any trailing newlines and break it up by the space
character... so we end up with:

    
    
    [['Xantippe', '09:00', '11:00'], ['Erica', '10:00', '12:06'], ['Marcia', '09:30', '11:45'], ['Elizabeth', '10:15', '12:10'], ['Angela', '11:30', '13:45'], ['Freda', '12:00', '14:20'], ['Maria', '12:30', '14:10']]
    

Then, we can use the `.sort` method of a `list` \- `itemgetter` is a handy
method for getting the nth element of a sequence, so we have name, start, end,
where end is the 2nd index (based on zero being the first, which will be the
name)

    
    
    from operator import itemgetter
    lines.sort(key=itemgetter(2))
    

And we end up with:

    
    
    [['Xantippe', '09:00', '11:00'], ['Marcia', '09:30', '11:45'], ['Erica', '10:00', '12:06'], ['Elizabeth', '10:15', '12:10'], ['Angela', '11:30', '13:45'], ['Maria', '12:30', '14:10'], ['Freda', '12:00', '14:20']]
    

Then write it back out:

    
    
    with open('output.txt', 'w') as fout:
        for el in lines:
            fout.write('{0}\n'.format(' '.join(el)))
    

