如何检查两个字符串是否在文件的同一行上?

时间:2018-11-07 14:51:16

标签: python python-3.x

我有一个程序,我在其中询问用户其用户名和密码,并检查文件以查看他们是否具有正确的用户名和密码。每个用户名和密码都存储在自己的行中。

这就是我所拥有的

if username and password in open("logininfo").read():
    print("logged in succesfully")
else:
    print("Incorrect username or password")

我遇到的问题是任何用户名都可以与任何密码一起使用,因为它可以检查整个文件。有什么方法可以检查它们是否在文件中的同一行?

4 个答案:

答案 0 :(得分:1)

您可以轻松地使此功能逐行检查文件

def check_password(username, password, lines):
     for line in lines:
         if username in line and password in line:
             return True
     return False

您可以通过以下方式使用此功能:

check_password(username, password, open(file_name).readlines())

答案 1 :(得分:0)

遍历open('logininfo').readlines(),检查用户名是否在一行中,密码是否在一行中。

if username and password in open("logininfo")中,它检查字符串username是否不为空或None(这不是故意的),因此您需要分别检查用户名和密码,如下所示:< / p>

if (username in line) and (password in line):
    ...

资源:

答案 2 :(得分:0)

请注意,您的代码不会执行您认为的操作。它根本不会检查用户名,只会检查用户名是否为“ False”。

这就是您想要的:

def checkpw():
    for line in open("foobar"):
        if line == (username + " " + password):
            print("logged in succesfully")
            return
    print("Incorrect username or password")

,但我强烈建议您对此类任务使用某种类型的库。您可能至少应该对密码进行哈希处理。这段代码是个糟糕的主意。

答案 3 :(得分:0)

您可以逐行检查它。完成操作后,别忘了关闭文件或在with语句中打开文件以释放资源。

def check_user(user, password):
    with open('loginfo', 'r') as file:
        for line in file:
            if user in line and password in line:
                return True

    return False
相关问题