Sheena Wadhwa Sheena Wadhwa - 4 months ago 29
Python Question

Finding a name in a CSV file

I have code that finds the input name in a CSV if it is present it says yes else no. But I entered a name present in the CSV yet it still says no.

Here is the code:

import csv

f=open("student.csv","r")
reader=csv.reader(f)
for row in reader:
print
studentToFind = raw_input("Enter the name of sudent?")
if studentToFind in reader:
print('yes')
else:
print('no')
f.close()

Answer

Simply ask the question before you loop over the file:

import csv

studentToFind = raw_input("Enter the name of student?")

f=open("student.csv","r")
reader=csv.reader(f)
found = "No"
for row in reader:
    if studentToFind in row:
        found = "Yes"

f.close()

print('{}'.format(found))