0

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()
dimo414
  • 47,227
  • 18
  • 148
  • 244

3 Answers3

2

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))
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • it works if i enter the name that is not present "NO". But when i enter the name that is present in the csv then output is both "Yes" "NO" – Sheena Wadhwa Jul 13 '16 at 05:29
2

You've got a couple of issues:

First reader is empty at this point, since you've already looped over its elements. Reading from a file is a one-time deal, if you want to access its contents more than once you need to write it to a data structure, e.g.:

rows = []
with open("student.csv", newline='') as csvfile:
  reader = csv.reader(csvfile)
  for row in reader:
    rows.append(row)

However this also won't be sufficient, because rows is now a 2D list, as each row the reader returns is itself a list. An easy way to search for a value in nested lists is with list comprehensions:

if studentToFind in [cell for row in rows for cell in row]:
  print('yes')
else:
  print('no')

Put it together, so the indentation's easier to see:

rows = []
with open("student.csv", newline='') as csvfile:
  reader = csv.reader(csvfile)
  for row in reader:
    rows.append(row)

if studentToFind in [cell for row in rows for cell in row]:
  print('yes')
else:
  print('no')
Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244
0

You've already iterated over the file once. When you try to loop over reader again there is nothing to loop over.

Instead don't even use the csv module and save the lines in the file into a list:

with open("student.csv","r") as f:
    lines = []
    for line in f:
        lines.append(line.rstrip())

studentToFind = raw_input("Enter the name of student?")
if studentToFind in lines:
    print('yes')
else:
    print('no')
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223