-2

I would like to sort content from a a text file. I have already sorted them by alphabetical order (name). The problem i am getting is that when I try to sort the scores in ascending or decending order, the program does not recognise the 10 as a 10 but as a 1. I have attached my code and text file.

Python 3.4 Code:

import csv
import operator

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


def menu():
    print('To Check The scores by ALPHABETICLE Order  [1]')
    print('To Check The Scores In ASCENDING Order   [2]')
    print('To check the AVERAGE Scores of Each Student  [3]')
    choice=int(input(':'))
    if choice==1:
        alpha()
        
    elif choice==2:
        ascend()
    
def alpha():
    quizGrades = open('Quiz-1.txt' , 'r')

    grades = csv.reader(quizGrades, delimiter =',')

    sortedGrades = sorted(grades, reverse= False, key=operator.itemgetter(1))

    for eachline in sortedGrades:
        print()
        print (eachline)
        quizGrades.close()

def ascend():
        quizGrades = open('Quiz-1.txt' , 'r')

        grades = csv.reader(quizGrades, delimiter =',')

        sortedGrades = sorted(grades, reverse= False, key=operator.itemgetter(4))

        for eachline in sortedGrades:
            print()
            print (eachline)
            quizGrades.close()

                      
menu()

Text file has (Edit: changed names for annonymity sake)

    Name:,Aum Patel,Class:1,Score:,10,/10
    Name:,Lolly Pop,Class:1,Score:,9,/10
    Name:,Kimjon Un,Class:1,Score:,5,/10
    Name:,Preet Are,Class:1,Score:,7,/10
    Name:,Aum Patel,Class:1,Score:,8,/10
    Name:,Bab Singh,Class:1,Score:,2,/10
    Name:,Kimjon Un,Class:1,Score:,1,/10
    Name:,Aum Patel,Class:1,Score:,10,/10
    Name:,Chong Singh,Class:1,Score:,1,/10
    Name:,Bab Singh,Class:1,Score:,7,/10
    Name:,Ak Chan,Class:1,Score:,8,/10
3
  • 1
    the csv reader is taking each field as a string, you need to convert to int or float - this will be necessary when you do average (also the '/10' will need to be parsed and converted also)
    – gkusner
    Nov 17, 2015 at 14:08
  • 3
    Welcome to StackOverflow! It's generally a good idea to limit the code in your question to only what you need help on. In your case, you could simplify down to only your ascend function (the one that isn't working for you) and remove things such as your menu. Be sure to checkout the tour for more information. stackoverflow.com/tour
    – Brian J
    Nov 17, 2015 at 14:10
  • 2
    Hi, Please do not deface your answer after you have taken help from it. It is like cutting down a tree after taking shelter below it. Please allow the other future users to gain from the knowledge. The answerers would have put a lot of effort. Do not put their valuable time to waste. Nov 24, 2015 at 12:17

2 Answers 2

1

you need to convert string which read from txt file to integer

grades = [int(grade) for grade in grades]

if you compare string, the result would be as follow

numString = ["1","5000","3","6","30","4","2","200"]
print(sorted(numString))

['1', '2', '200', '3', '30', '4', '5000', '6']
1

You're sorting the numbers as strings, rather than as numbers. You need to change your ascend() function as follows:

def ascend():
        quizGrades = open('Quiz-1.txt' , 'r')

        grades = csv.reader(quizGrades, delimiter =',')

        sortedGrades = sorted(grades, reverse= False, key=lambda x: int(x[4]))

        for eachline in sortedGrades:
            print()
            print (eachline)
            quizGrades.close()

The key=lambda x: int(x[4]) will convert the numbers to an integer for the sort without changing the output from a string.

Follow-up Comment

I would also suggest that a more common format for a CSV file would be:

"Name","Class","Score","Total Points"
"Aum Patel",1,10,10
...

The first row is your header row, subsequent rows just contain values, so that values don't need to be parsed out from labels on the same line of the text file. In using this format, and using quoting=csv.QUOTE_NONNUMERIC in your csv.reader() line, your original sort would have worked:

import csv
import operator

with open('Quiz-1.txt', 'r') as f:
    grades = csv.reader(f, delimiter=",", quoting=csv.QUOTE_NONNUMERIC)  # Treat any unquoted values as floats.
    next(grades)  # Skip the header row.
    sorted_grades = sorted(grades, reverse=False, key=operator.itemgetter(2))  # Just changed column.

for row in sorted_grades:
    print(row)
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.