我需要检查用户名和密码是否与文本文件中的详细信息匹配。我不确定该怎么做。这就是我到目前为止(将用户名保存到文件中)。
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")
答案 0 :(得分:0)
还有另一种使用with open
的方法在循环内完成这些过程之后关闭文件,因此您可以创建一个读取循环和一个附加循环。为此,我喜欢将名称和密码存储在同一行的想法,这样我们可以检查以确保名称和对应的密码相互链接,而不是能够对任何名称使用任何密码。同样,在使用append时,我们将不得不添加一个'\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