Jasper StaTham Jasper StaTham - 6 months ago 45
Python Question

Matching user input to file records in Python

i'm making a program that will ask a user to enter their student ID and it will display the student information such as student ID and their student name . i does this first by asking the user to enter their id and it will then read a .txt file and check if the student id is a matched then it will print out the content of my .txt file information of the specific student that the user is looking for.

this is my content of the file

201707001 Michael_Tan
201707002 Richard_Lee_Wai_Yong
201707003 Jean_Yip
201707004 Mark_Lee
201707005 Linda_Wong
201707006 Karen_Tan
201707007 James_Bond
201707008 Sandra_Smith
201707009 Paul_Garcia
201707010 Donald_Lim


this is my source code

# user can find out the student info
userInput = input("Please enter a student ID: ")

# read the students file
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
studentFile = f.readlines()
for student in studentFile:
stdId, stdName = student.strip().split(" ",1)


# check if the student exist
matched = True

while matched:
if userInput == stdId:
print("True")
else:
print("False")
matched = False
break


but the output i get is false even though i type the exact studentID

Answer Source

You should perform your checks as you read your file. Otherwise, you are splitting and obtaining your information, but this data is lost in the subsequent iteration. Try this:

with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
    studentFile = f.readlines()
    for student in studentFile:
        stdId, stdName = student.strip().split()
        if userInput == stdId:
            print(stdName)
            break

Better still, for large files, iterate line-wise. Do not use f.readlines because it loads all your data into memory.

with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
    for line in f:
        stdId, stdName = line.strip().split()
        if userInput == stdId:
            print(stdName)
            break
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download