1

Python 3.5.1 I am creating a program that sorts a text file. The program should re-write the text file to keep only the three latest scores for each student. I currently have 4 scores for 'Aum Patel' in the text file; I want python to remove the oldest version of the score before it has been read. The text file is as follows-> 'name','score'

This is the text file (it is called 'Quiz-1'):

Aum Patel,10
Guy,9
Aum Patel,8
Bob Singh,2
Aum Patel,4
Aum Patel,10
Chong Singh,1
Bob Singh,7

And this is the Python 3 code:

import csv
import operator

n=0
quizGrades = open('Quiz-1.txt' , 'r')

grades = csv.reader(quizGrades, delimiter =',')
sortedGrades = sorted(grades, reverse= False, key=operator.itemgetter(0))
person=[]
SCORE=[]
for eachline in sortedGrades:
    person.append(eachline[0])
    SCORE.append(eachline[1])
    print(person[n],': scored ',SCORE[n])
    print()
    n=n+1
    quizGrades.close()
3
  • 1
    Which one is the oldest…? Commented Feb 14, 2016 at 12:05
  • why do you not want the older scores to be read? and how do you know which is older? Commented Feb 14, 2016 at 12:18
  • i want the newer ones to be read. the newer ones are at the top Commented Feb 14, 2016 at 13:47

1 Answer 1

1

To keep track of the various students, I would recommend using a dictionary to store everything. Each entry would then contain a list of all of their scores.

So first read the quiz file in, and build up the dictionary. Then iterate over all of the entries writing out up to the last 3 from each as follows to your new file:

import csv

d_students = {}

with open('input.txt', newline='') as f_input, open('output.txt', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    for student, score in csv_input:
        if student in d_students:
            d_students[student].append(int(score))
        else:
            d_students[student] = [int(score)]

    for student, scores in d_students.items():
        scores = scores[-3:]    # Take the last 3 scores in each list
        print("Student {} has an average score of {:.1f}".format(student, sum(scores) / float(len(scores))))

        for score in scores:
            csv_output.writerow([student, score])

For the data you have d_students would hold the following:

{'Guy': ['9'], 'Amanjeet Singh': ['2', '7'], 'Chong Singh': ['1'], 'Aum Patel': ['10', '8', '4', '10']}

The averages are calculated by summing the scores and dividing by the total number of scores in each list, this would display the following output:

Student Amanjeet Singh has an average score of 4.5
Student Chong Singh has an average score of 1.0
Student Aum Patel has an average score of 7.3
Student Guy has an average score of 9.0

From here, the script outputs the last 3 entries from each list giving you the following output file:

Chong Singh,1
Guy,9
Amanjeet Singh,2
Amanjeet Singh,7
Aum Patel,8
Aum Patel,4
Aum Patel,10

Note, if you are using csv with Python 3, you need to open the file using the newline='' parameter.

Sign up to request clarification or add additional context in comments.

4 Comments

The line for score in scores[-3:] will do this for you. This takes at most the last 3 entries in each student's list of scores. If you run this script, it will create you a new file called output.txt with just the last 3 entries from each student. As a dictionary is used, the ordering of the students might change, but the scores will remain in order.
It prints out the entries nearest the bottom of your file. If you want the ones nearest the top of your file change [-3:] to [:3]. I suggest you change your test file to have different numbers e.g. make the first entry say 15, you would then see which are included in the output. At the moment you have two with 10 so you can't tell which is which.
What do I need to do if I want to find out the average score for each individual student(from the three scores)
As you have the list of scores, you can print the average by using Python's sum() function and dividing by the length of the list. I have updated the answer to show how this could be done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.