Comparing csv file values with Input Values

Viewed 33

I have a csv file with names and ID's, i want user to input their name and ID and program will check whether they are present in csv file or not.

The problem is if iam checking it wrt one column,iam getting correct answer.

import csv

with open('attendance_data/detail.csv') as file:  # correct answer
    reader = csv.reader(file)
    name = input('Enter Name:')
    id = int(input('Enter ID:'))
    for row in reader:
        if row[1] == name:
            # print(row[0],row[4])
            print('you are already registered')
            break
    else:
        print('incorrect')

But when iam checking it wrt to two columns,iam getting incorrect answer.

import csv

with open('attendance_data/detail.csv') as file:    # incorrect answer
    reader = csv.reader(file)
    name = input('Enter Name:')
    id = int(input('Enter ID:'))
    for row in reader:
        if (row[1] == name and row[0] == id):
            # print(row[0],row[4])
            print('you are already registered')
            break
    else:
        print('incorrect')
1 Answers

The problem is you are comparing string to integer. Convert row[0] to integer and it will work:

import csv

with open("attendance_data/detail.csv") as file:
    reader = csv.reader(file)
    name = input("Enter Name:")
    id_ = int(input("Enter ID:"))  # <--- id_ is of type int
    for row in reader:
        if row[1] == name and int(row[0]) == id_:  # <--- convert row[0] to int
            print("you are already registered")
            break
    else:
        print("incorrect")
Related