python - 从文本文件检查用户名和密码是否正确
问题描述
我需要检查用户名和密码是否与文本文件中的详细信息匹配。我不知道该怎么做。这是我到目前为止所拥有的(将用户名保存到文件中)。
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")
解决方案
在循环内完成过程后,还有另一种方法使用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
推荐阅读
- java - 将 3 个链表合并为 1 个(Java)
- javascript - 如何在加载网页时隐藏 div
- ms-access - 标准中的 OnlyDigits 函数
- ubuntu - 无法使用 nginx 将子目录重定向到子域
- android - 我可以更改 ArCore 虚拟相机的姿势或在一个场景中有多个虚拟相机吗?
- powershell - Powershell:关于 %(百分号)的问题以及它在以下脚本片段中的工作方式
- elasticsearch - 将数据从 elasticsearch 传输到 kafka
- python - 没有名为 sh 的模块
- javascript - 处理 ReferenceError:geoip2 未在 jQuery 或 JavaScript 中定义
- excel - Excel中多个工作表的增量索引