Append your data to a list, say d
.
Sort it with the third item(4th column) of the list. Reference - operator.itemgetter
Write the sorted data to your output file.
Contents of input file
[kiran@localhost ~]$ cat infile.txt
Baltimore, 93, 69
Boston, 69, 93
New York, 95, 67
Tampa Bay, 90, 72
Toronto, 73, 89
Code::
>>> from operator import itemgetter
>>> d=[]
>>> with open('infile.txt','r') as infile:
... for line in infile.readlines():
... data = line.strip().split(',')
... wins = int(data[2])
... percentage = 162 / float(wins)
... data.append(str(round(percentage, 3))) #add percentage to your list that already contains the name and two scores.
... d.append(data) # add the line to a list `d`
...
>>> print d
[['Baltimore', ' 93', ' 69', '2.348'], ['Boston', ' 69', ' 93', '1.742'], ['New York', ' 95', ' 67', '2.418'], ['Tampa Bay', ' 90', ' 72', '2.25'], ['Toronto', ' 73', ' 89', '1.82']]
>>> d.sort(key=itemgetter(3)) #sort the list `d` with the third item(4th column) of your sublist.
>>> print d
[['Boston', ' 69', ' 93', '1.742'], ['Toronto', ' 73', ' 89', '1.82'], ['Tampa Bay', ' 90', ' 72', '2.25'], ['Baltimore', ' 93', ' 69', '2.348'], ['New York', ' 95', ' 67', '2.418']]
>>> #write the items in list d to your output file
>>>
>>> with open('outfile.txt','w') as outfile:
... for line in d:
... outfile.write(','.join(line)+'\n')
...
>>>
Content of output file:
[kiran@localhost ~]$ cat outfile.txt
Boston, 69, 93,1.742
Toronto, 73, 89,1.82
Tampa Bay, 90, 72,2.25
Baltimore, 93, 69,2.348
New York, 95, 67,2.418