I have the following code, and am attempting to sort the file contents in the simplest method possible.
import csv
import operator
#==========Search by ID number. Return Just the Name Fields for the Student
with open("studentinfo.txt","r") as f:
studentfileReader=csv.reader(f)
id=input("Enter Id:")
for row in studentfileReader:
for field in row:
if field==id:
currentindex=row.index(id)
print(row[currentindex+1]+" "+row[currentindex+2])
#=========Sort by Last Name
with open("studentinfo.txt","r") as f:
studentfileReader=csv.reader(f)
sortedlist=sorted(f,key=operator.itemgetter(0),reverse=True)
print(sortedlist)
I am aware of various possible solutions but cannot quite get them to function correctly, and would also, for teaching/learning purposes, be interested in the most simple and effective solution with a clear explanation.
Research included: ****import operator**** sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
or use of lambda sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)
For the ANSWER, I would be grateful if someone could post a full working solution, showing sorting by LAST NAME, and by ID Number, to illustrate two different examples. An extension to the answer would be to show how to sort by multiple values in this specific example:
Full code listing:
Contents of File
002,Ash,Smith,Test1:20,Test2:20,Test3:100003
004,Grace,Asha,Test1:33,Test2:54,Test3:23
005,Cat,Zelch,Test1:66,Test2:22,Test3:11
001,Joe,Bloggs,Test1:99,Test2:100,Test3:1
003,Jonathan,Peter,Test1:99,Test2:33,Test3:44