python - 正确循环读取数据、比较数据和从 txt 文件写入数据
问题描述
有人可以就我遇到的以下问题提供一些建议。
我需要让用户输入用户名,然后输入密码。然后,我需要将用户名和密码与存储了正确用户名和密码的外部 txt 文件进行比较。对于编程方面,我需要创建一个循环,直到输入正确的用户名,然后输入正确的密码。我还需要显示用户名是否正确但密码不正确。我只是在努力选择使用哪个循环以及如何构造这段代码。
文本文件包含:
管理员,管理员1
admin 是用户名 admin1 是密码
我到目前为止的代码在下面,它工作正常,但它不包含正确的循环。
with open('user.txt')as username:
contents = username.read()
user = input("Please enter your username:")
if user in contents:
print("Username correct")
else:
print ("Username incorrect. Please enter a valid username")
解决方案
撇开验证密码的方法不谈,您可以执行以下操作。首先,您将用户名和密码收集到字典中users
(键:用户名,值:密码)。然后,您使用 while 循环检查用户的输入是否与此字典键(使用not in users
)匹配,直到输入匹配。
users = {} # dictionary that maps usernames to passwords
with open('user.txt', 'rt') as username:
for line in username:
uname, password = line.split(",")
users[uname.strip()] = password.strip() # strip removes leading/trailing whitespaces
uinput = input("Please enter your username:")
while uinput not in users:
print("Username incorrect. Please enter a valid username")
uinput = input("Please enter your username:")
# do stuff with password etc.
推荐阅读
- python - python matplotlib问题使其从左到右
- terminal - 终端的快捷方式不适用于糟糕的大苏尔
- c# - 无法将当前 JSON 对象反序列化为“System.Collections.Generic.List”类型,因为该类型需要 JSON 数组才能正确反序列化
- laravel - 无法再在 laravel 8 中安装任何作曲家
- python - 如何使用 SSL 在 RHEL 上编译 python3?无法导入 SSL
- sql - 为什么 Oracle 给出十进制 9999.99999999999 而不是 10000?
- snowflake-cloud-data-platform - 雪花错误“SQL 编译错误:空 SQL 语句。”
- vue.js - Vue.js Vuetify 复选框到芯片组
- r - 更新软件包时出错
- google-workflows - Google Cloud Workflows - 并发执行限制