比较用户输入与文本文件

时间:2020-01-17 19:55:27

标签: python

from pip._vendor.distlib.compat import raw_input

class Login:

    def logging_in(self):

        StudentID = raw_input("please enter your student id. ")
        f = open("StudentDetails.txt", "r+")
        lines = f.readlines()
        if StudentID == lines:
            print("Verified Welcome")
        else:
            print("you are not a registered Student Goodbye")
            f.close()

login = Login()

login.logging_in()

enter image description here

我试图将用户输入与文本文件中的变量进行比较。每次我不想输入学生证(0001,0002)时,它都会一直打印,您不是注册的学生再见。该如何解决?

2 个答案:

答案 0 :(得分:1)

创建实例后,您可以加载一次有效的ID。然后,当用户尝试登录时,您只需检查该集合中是否存在ID。例如:

from pip._vendor.distlib.compat import raw_input

class Login:

    def __init__(self):
        with open("StudentDetails.txt", 'r') as file:
           lines = file.readlines()
        self.valid_ids = set([s.strip() for s in lines])

    def logging_in(self):

        StudentID = raw_input("please enter your student id. ")
        if StudentID.strip() in self.valid_ids:
            print("Verified Welcome")
        else:
            print("you are not a registered Student Goodbye")

login = Login()

login.logging_in()

答案 1 :(得分:0)

您正在将输入ID与列表进行比较,您需要添加一个for循环 def logging_in(self):

    StudentID = raw_input("please enter your student id. ")
    f = open("StudentDetails.txt", "r+")
    lines = f.readlines()
    for line in lines
        if StudentID in line:
            print("Verified Welcome")
        else:
            print("you are not a registered Student Goodbye")
            f.close()

顺便说一句,就像@Cohan在评论中说的那样,任何一行字符都可以访问用户。我假设这只是出于学习目的,而不是真正的安全性方法。

相关问题