根据用户输入在文本文件中搜索特定数据

时间:2017-09-19 20:44:03

标签: python function file search io

我是Python的新手并且已经搜索了如何执行此操作,但我找不到解决方案。我有一个充满学生姓名的文本文件,我希望能够输入学生证并提供该学生的记录。我试着将它放入一个函数中。在任何帮助之前都要感谢。

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]))

2 个答案:

答案 0 :(得分:1)

假设要读取的文件保持不变,您只需将ID作为参数传递即可。除print转换为return外,其他所有内容都保持不变。另外,我建议使用with...as来处理文件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))

答案 1 :(得分:0)

由于您使用的是 rstrip()功能,因此您应该注意不要无意中修改学生ID。

接受函数外部的数据并将其传递给函数是一种好习惯。换句话说,如果您接受学生ID通常会更好,

StudentId=input("Enter Student ID: ")

然后,您可以将其传递给您创建的函数,以便只计算ID并返回名称和其他详细信息。

SrcStudent(StudentId)

要定义功能,请使用 def 关键字。

def function_name(parameter): (lines of codes)

这样的事情可能是,

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]))