Can anyone explain the root of this index out of range error?

Viewed 469

The following code throws up a mysterious error that I cannot find the solution to. It works fine when I tested it in a bigger module, so cannot see why this doesn't work:

Code

import csv

with open('studentinfo.txt','a') as fo: #open the file in append mode (add to file, we don't wish to overwrite!)
        studentfileWriter=csv.writer(fo) #fo = file out (this can be called anything you like)
        id=input("Enter Student Id:")
        firstname=input("Enter firstname:")
        surname=input("Enter Surname:")
        test1=input("Enter test1 score:")
        test2=input("Enter test2 score:")
        test3=input("Enter test3 score:")
        studentfileWriter.writerow([id,firstname,surname,"Test1:"+test1,"Test2:"+test2,"Test3:"+test3])
        print("Record has been written to file")


with open("studentinfo.txt", "r") as f:
    reader = csv.reader(f)
    sorted_list = list(reader)  # turn the reader iterator into a list
    sorted_list.sort(key=lambda x: x[2])  # use the third column as a sorting key
    print("\n".join(str(row) for row in sorted_list))  # prettier print

Error Message

sorted_list.sort(key=lambda x: x[2])  # use the third column as a sorting key
IndexError: list index out of range

It is worth noting that the code works fine when there are no additions to the file contents. On adding a student to the file, the SORT does not work.

Original File contents

001,Joe,Bloggs,Test1:99,Test2:100,Test3:1
002,Ash,Smith,Test1:20,Test2:20,Test3:100
003,Jonathan,Peter,Test1:99,Test2:33,Test3:44

File Contents on adding a test student:

001,Joe,Bloggs,Test1:99,Test2:100,Test3:1
002,Ash,Smith,Test1:20,Test2:20,Test3:100
003,Jonathan,Peter,Test1:99,Test2:33,Test3:44
006,Mulch,Cart,Test1:99,Test2:22,Test3:11

The resultant error occurs at this stage (when the new student has been added). The sort function otherwise works fine.

Update and clarification:

For teaching purposes, I need it to work both on repl.it AND IDLE>

If someone could post a repl.it as an answer (With my code above, working), which also works when implemented in IDLE with a txt file, I will accept as an answer.

1 Answers
Related