写入错误时程序不会打印“用户名或密码错误”

时间:2019-06-16 13:01:54

标签: python python-3.x authentication

我正在做一个有效的登录注册程序,它将写入一个.txt文件,然后确认要登录。问题是,如果我输入用户名和密码,它不会显示“用户名或密码错误”命令,如果用户名错误,它将关闭。

print("Hello")
user = input("Do you have an account? y/n: ")
from getpass import getpass

#Function if you dont have an account
if user == "n":
    while True:
        username = input("Enter a username: ")
        password = input("Enter a password: ")
        password1 = input("Confirm your password: ")
        if password == password1:
            file = open(username+".txt", "w")
            file.write(username+":"+password)
            file.close()
            user = "y"
            break
        print("Passwords do NOT match")

#Function if you have an account
if user == "y":
    while True:
        username = input("Login: ")
        password = getpass("Password: ")
        file = open(username+".txt", "r")
        data = file.readline()
        file.close()
        if data == username+":"+password:
            print("Welcome", username)
            input("Press Enter to continue")
            break
        print("Incorrect username or password")

1 个答案:

答案 0 :(得分:0)

根据我的评论:这是因为您的文件名是username.txt。因此,如果输入错误的用户名,则会出现错误FileNotFoundError。但是它可以正常工作,如果您使用错误的密码输入了正确的用户名,它将得到Incorrect username or password。因此,您需要制作一个pass.txt的文件,并将其用于读写。

user = input("Do you have an account? y/n: ")
from getpass import getpass

filename = 'pass.txt'
#Function if you dont have an account
if user == "n":
    while True:
        username = input("Enter a username: ")
        password = input("Enter a password: ")
        password1 = input("Confirm your password: ")
        if password == password1:
            file = open(filename, "a")
            file.write(username+":"+password)
            file.write("\n")
            file.close()
            user = "y"
            break
        print("Passwords do NOT match")

#Function if you have an account
if user == "y":
    d = {}
    with open(filename) as f:
        d = dict([line.rstrip().split(':') for line in f])
    while True:
        username = input("Login: ")
        password = getpass("Password: ")

        if (username in d and d[username] == password):
            print("Welcome", username)
            input("Press Enter to continue")
            break
        print("Incorrect username or password")