首页 > 解决方案 > 从文本文件检查用户名和密码是否正确

问题描述

我需要检查用户名和密码是否与文本文件中的详细信息匹配。我不知道该怎么做。这是我到目前为止所拥有的(将用户名保存到文件中)。

print("Are you a returning player?")
user = input()
if user.lower() == "no":
    username = input("Please enter a username for your account.\n")
    password = input("Please enter a password for your account.\n")
    file = open("account.txt","a")
    file.write(username)
    file.write("\n")
    file.write(password)
    file.close()

else:
 user_name = input("Please enter your username.\n")
 pass_word = input("Please enter your password.\n")

标签: python

解决方案


在循环内完成过程后,还有另一种方法使用with open关闭文件,因此您可以创建读取循环和附加循环。为此,我喜欢将名称和密码存储在同一行的想法,这样我们可以检查以确保名称和相应的密码相互关联,而不是能够为任何名称使用任何密码。此外,当使用 append 时,我们将不得不添加 a'\n'或我们write将写入同一行的所有内容

为了验证用户,我们打开文件r,然后我们可以使用从那里for line in f获取所有行,.txt我们可以遍历每一行,如果用户名和密码都存在于同一行中,我们可以欢迎用户,如果不发送他们回到起点。

希望这可以帮助!

while True:
    user = input('\nAre you a returning player: ')
    if user.lower() == 'no':
        with open('accounts.txt', 'a') as f:
            username = input('\nEnter username: ')
            password = input('Enter password: ')
            combo = username + ' ' + password
            f.write(combo + '\n')

    else:
        with open('accounts.txt', 'r') as f:
            username = input('\nEnter username: ')
            password = input('Enter password: ')
            for line in f:
                if username + ' ' + password + '\n' == line:
                    print('Welcome')
                    break
            else:
                print('Username and/or Password Incorrect')
Are you a returning player: no

Enter username: vash
Enter password: stampede

Are you a returning player: yes

Enter username: vash
Enter password: stacko
Username and/or Password Incorrect

Are you a returning player: yes

Enter username: vash
Enter password: stampede
Welcome

推荐阅读