Order a text file in alphabetical order using the second column in Python

572 Views Asked by At

I have tried all kinds of ways to get the text file to order alphabetically by the last name. The last name is currently read as column two of each split line. I can sort by column one without a problem. I try to put last.sort() or use the sorted(myList) but it doesn't work. I have even tried importing itemgetter. Please help! Pictures of results... previous results with column one sorted... Picture of Text File

TXT FILE INFO: 654,Jones,1,18:03 733,Smith,3,18:09 394,Jackson,4,18:22 876,Cole,1,18:23 555,Cruz,5,18:28 741,Martinez,2,18:33 499,Davis,2,18:36 338,Blunt,3,18:44 632,Patton,5,18:45 712,Joyce,4,18:49 112,Shoemaker,1,18:55 321,Smart,5,18:58 564,Love,2,19:01 843,Grove,4,19:05 933,Ham,3,19:10

with open("Race_Results_Sample.txt", "r")as myList:
    myList= myList.read().split()
    sorted(myList, key=lambda kv: kv[1])
    for line in myList:
        num, last, org, time = line.split(",")
        print num, last, org, time
1

There are 1 best solutions below

1
On BEST ANSWER

Try parsing the text into a 2d List, something like

with open("test.txt", "r")as myList:
    myList = myList.read()
    myList = [l.split(",") for l in myList.splitlines()]
    myList = sorted(myList, key=lambda kv: kv[1])
    for line in myList:
        num, last, org, time = line
        print num, last, org, time

Split per linebreak and then again for each line per comma.