首页 > 解决方案 > 正确循环读取数据、比较数据和从 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") 

标签: pythonloopspasswords

解决方案


撇开验证密码的方法不谈,您可以执行以下操作。首先,您将用户名和密码收集到字典中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.

推荐阅读