0

I've got some information stored in a text file based on people taking a test and the scores they have received. Every time they take the test again, a new score is added. The text file looks like this with the data stored within it:

Mike 5 7 9
Terry 6 6 9
Paul 4 5 6

I'd like to be able to retrieve the information from the text file and identify the highest score for each person so that it printed out their name and a single number.

If I retrieve the data from the file and store it as a list using this code:

with open("classa.txt") as f:
   content = f.readlines()
   print(content)

then the data is printed out like this: ['Mike 5 7 9\n', 'Terry 6 6 9\n', 'Paul 4 5 6']

I'm guessing that I really need to create several nested lists within a list. One for each person but i'm unsure how to accomplish this or how to parse the data so that I can work with it in columns and ignore the "Name" column when dealing with the numeric values that follow it.

Would it be better if the data in the text file was comma delimited so that it read like this:

Mike,5,7,9
Terry,6,6,9
Paul,4,5,6

Any help would be appreciated. I'm a little out of my depth with it.

Alexander
  • 1,969
  • 19
  • 29
mjolnir
  • 61
  • 1
  • 1
  • 11

1 Answers1

2
with open("names.txt") as f:
    # splitlines of the content
    content = f.read().splitlines()
    for line in content:
        # split at spaces
        splittedLine = line.split(" ")

        # get the first element which is the name
        name = splittedLine[0]

        # get the all the elements except the first
        scores = splittedLine[1:]

        # get the last element of the sorted list which is the highscore
        highscore = sorted(scores)[-1]
        print("{} : {}".format(name, highscore))

I commented the code so i hope everything is understandable.

Output:

Mike : 9

Terry : 9

Paul : 6

jvecsei
  • 1,936
  • 2
  • 17
  • 24
  • That's excellent. Thanks so much. I'll give it a try first thing in the morning when I get back to a computer. – mjolnir Nov 17 '15 at 00:13