简体   繁体   中英

Search for specific data in a text file based on user input

I am new to Python and have searched for how to do this, but I can't find a solution. I have a text file full of students names, and I want to be able to enter a student ID and bring up a record of that student. I tried to put it into a function. Thanks in advance of any help.

search = input("Please enter a student ID: ")
file = open("Students.txt", 'r')
for i in file:
    data = i.rstrip()
    data = data.split(",")
    if(ID == data[0]):
        print("\nThe student you require is: {} {} \n".format(data[2],data[1]))

Assuming the file to read remains constant, you could just pass ID as a parameter. Everything else remains the same, except the print is converted to a return . Also, I would recommend using with...as to handle file I/O.

def SearchStudent(ID):
    with open("Students.txt", 'r') as file:
        for i in file:
            data = i.rstrip().split(",")
            if data[0] == ID:
                return "The student you require is: {} {}".format(data[2], data[1])

    return "No matches found"

search = input("Please enter a student ID: ")
print(SearchStudent(search))

Since you are using the function rstrip() , you should be careful that you are not unintentionally modifying the student ID.

It is a good practice to accept the data outside the function and pass it into the function. In otherwords, it would be better if you accept the student ID normally like,

StudentId=input("Enter Student ID: ")

Then you can pass it into the function that you create to just tally the ID and return the name and other details.

SrcStudent(StudentId)

To define a function use the def keyword.

def function_name(parameter): (lines of codes)

Something like this may be,

def SrcStudent(ID): with open("Students.txt", 'r') as file: for f in file: data = f.strip().split(",") if (data[0] == ID): print("The student you require is: {0} {0}".format(data[2], data[1]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM