正确循环读取数据、比较数据和从txt文件写入数据
Correct loop to read data, compare data and write data from txt file
有人可以就我遇到的以下问题提供一些建议吗?
我需要要求用户输入用户名和密码。然后我需要将用户名和密码与存储了正确用户名和密码的外部 txt 文件进行比较。
对于编程方面,我需要创建一个循环,直到输入正确的用户名,然后再输入正确的密码。如果用户名正确但密码不正确,我还需要显示。我只是在努力选择要使用的循环以及如何构建此代码。
文本文件包含:
admin, admin1
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.
有人可以就我遇到的以下问题提供一些建议吗?
我需要要求用户输入用户名和密码。然后我需要将用户名和密码与存储了正确用户名和密码的外部 txt 文件进行比较。 对于编程方面,我需要创建一个循环,直到输入正确的用户名,然后再输入正确的密码。如果用户名正确但密码不正确,我还需要显示。我只是在努力选择要使用的循环以及如何构建此代码。
文本文件包含:
admin, admin1
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.