Python Open File - 如果有其他声明

时间:2017-08-18 20:21:36

标签: python if-statement text with-statement

我对代码的输出感到困惑。

这是我的档案:

201707001 Jenson_ 
201707002 Richard 
201707003 Jean

这是我的代码:

def studentInfo (userInput):  # storing student info
    # read the students file
    with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
        for line in f:
            stdId, stdName = line.strip().split(" ", 1)
            # check if the student exist
            if userInput == stdId:
                print("Student found!")
                print("Student ID: " + stdId + "\nStudent Name: " + stdName)
            else:
                print("The student does not exist")


studentFinder = input("Please enter id: ")
studentInfo(studentFinder)

这是我输出的代码

Please enter id: 201707001
Student found!
Student ID: 201707001
Student Name: Jenson
The student does not exist
The student does not exist

如何修复代码?

1 个答案:

答案 0 :(得分:3)

您的services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(2); });声明过早发布。它将输出"找到"找到后,在下一行输出"未找到"!

你无法知道在找到文件结尾之前你找不到学生。

让我为else使用else对应方提出一个解决方案:

for

现在,如果找到了学生,请致电 for line in f: stdId, stdName = line.strip().split(" ", 1) # check if the student exist if userInput == stdId: print("Student found!") print("Student ID: " + stdId + "\nStudent Name: " + stdName) break else: print("The student does not exist") 。如果未调用break,则会输入break循环的else。不错的python功能,不是很有名的

(如果您想多次匹配,则不起作用。)

请注意,从长远来看,您可能希望将文件内容存储在字典中,以便多次搜索的查找速度更快:

for

现在with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f: d = dict(zip(line.split(" ",1) for line in f) 是您的ID =>名字字典,当你有很多要执行的查询时使用快速查找(文件只读一次,字典使用哈希进行快速搜索)