Reputation: 13
I am a complete novice, but I'm certain there must be a relatively simple solution for what I'm intending.
I'm just trying to match the first column in the CSV with the userinput, then when it finds a match it retrieves the next two values in the next two columns and assigns them to name and mark.
The user searches for the ID, the function sifts through the first index of every row, if it finds a match then it takes the next two columns in that row and puts it in 'name' and 'mark'.
The CSV file has entries on each new row formatted like this: 1,Bertrand,83 I've included the save function in case I've formatted it wrong.
I get the error IndexError: list index out of range I've searched for hours and have tried to implement 3 solutions and nothing seems to work.
import csv
class studentProfile:
def __init__(self, sid, name, mark):
self.sid = sid
self.name = name
self.mark = mark
def saveCsv(self):
with open("studentDB.csv", "a") as csvfile:
prowriter = csv.writer(csvfile, delimiter=",", quotechar="|")
prowriter.writerow([self.sid, self.name, self.mark])
print("Profile {}({}) saved.".format(self.name, self.sid))
def loadCsv(self):
search = input("Enter a Student ID to retrieve profile: ")
with open("studentDB.csv", "r") as csvfile:
csvloader = csv.reader(csvfile, delimiter=",", quotechar="|")
for row in csvloader:
if search == row[0]:
self.sid = search
self.name = row[1]
self.mark = row[2]
EDIT: Used to have:
search = list(input("Enter a Student ID to retrieve profile: "))
Now corrected but the error persists:
Enter a Student ID to retrieve profile: 2 Traceback (most recent call last): File "C:\Users\techn\Desktop\python workspace\zzzmypro\garbagebench.py", line 83, in p1.loadCsv() File "C:\Users\techn\Desktop\python workspace\zzzmypro\garbagebench.py", line 48, in loadCsv if search == row[0]: IndexError: list index out of range
Upvotes: 1
Views: 417
Reputation: 1173
Why did you put list
to get the search
tho?
You should change to search = input("Enter a Student ID to retrieve profile: ")
and it works like a charm then. Here is your code with a little change to debug
Upvotes: 1