试图根据存储在文件中的内容检查用户详细信息输入?

时间:2017-11-07 18:07:09

标签: python

我有123123保存在userdetails.txt中,我总是输入123作为用户名,123输入密码。我没有输出。“

我只需要一个接受用户名和密码的程序,然后验证它以测试它是否在文本文件中找到。

到目前为止,我已经提出了这个问题。

new = input("Do you have an existing username and password? Enter Y/N: ")

userdetails = open("userdetails.txt","r+")

if new == "Y":

username = input("Enter username: ")

password = input("Enter password: ")

for line in userdetails:

    usn = userdetails.readline

    if usn == username:

        print("Username authenticated")

        break

        usn = "v"

for line in userdetails:

    psw = userdetails.readline

    if psw == password:

        print("Password authenticated")

        break

        psw = "v"

if usn == "v" and psw == "v":

    authentication = True

    print("Authentication succesful..")

2 个答案:

答案 0 :(得分:1)

对代码进行一些小的清理工作。这应该得到您想要的输出(请注意,用户名和密码由我创建的userdetails.txt文件中的':'分隔,如下所示:' 123:456') :

username = '123'
password = '456'
usn = 'nv'
psw = 'nv'

with open("userdetails.txt","r+") as myfile:

    f = myfile.readlines()

    for line in f:

        if username == line.split(':')[0]:
            usn = "v"; print("Username authenticated")
            if password == line.split(':')[-1]:
                psw = "v"; print("Password authenticated")
                break
            else:
                print('Invalid password')

    if usn == "v" and psw == "v":
        authentication = True
        print("Authentication succesful")

答案 1 :(得分:1)

您的代码,只是检查userdetails.txt文件中是否存在任何用户名和密码。也就是说,它从用户获取用户名和密码并运行该文件以查看是否存在与用户名完全匹配的行。如果是,则打印"用户名已验证"。然后它继续读取文件,直到遇到密码匹配,如果是,则打印"密码验证"。

更好的实现方法是在同一行上有一个用户名和密码组合,例如

  

user1 password1

     

user2 password2

     

user3 password3

执行此操作会将特定用户名链接到其密码。如果您这样做,那么以下代码应该对用户进行身份验证。

new = input("Do you have an existing username and password? Enter Y/N: ")
userdetails = open("userdetails.txt", "r+")

if new == "Y":
    user_found = False
    input_username = input("Enter username: ").strip()
    input_password = input("Enter password: ").strip()

    for line in userdetails:
        username, password = line.split(' ')
        if input_username == username.strip():
            user_found = True
            print("User {0} is present in file".format(username))
            if input_password == password.strip():
                print("Authentication success!")
            else:
                print("Incorrect password for {0}".format(username))

            break

    if not user_found:
        print("Username {0} not found".format(input_username))