首页 > 解决方案 > 在文件python中搜索用户名

问题描述

我正在尝试从 txt 文件中查找用户名。(我知道这不是安全明智的,但它是出于测试目的)下面是我正在使用的代码,我从文件中的任何行中找到用户名,将其保存到列表中,然后验证该列表中的密码。但它只找到文件中的第一行。第 1 行之后的所有其他用户名都得到“找不到用户名”

with open("user.txt","r") as file:
        for line in file.readlines(): 
            login_info = line.rstrip("\n").split(", ")
            while True:
                username = input("Please enter your username: ")
                if username == login_info[0]:
                    print("Username found!\n")
                    while True:
                        password = input("Please enter your password: ")
                        if password == login_info[1]:
                            print("Password correct!\n")
                            print(f"Welcome {username}!\n")
                            return options()
                        else:
                            print("Password incorrect.")
                else:
                    print("Username not found.")

txt 文件如下所示:

管理员,adm1n 皮特
,p3t3
马克,m@rk

其中每一行都有用户名作为第一个字符串,后跟逗号,然后是密码。

如果有人可以帮助我或为我指出正确的方向以寻求答案。

标签: python

解决方案


您的代码存在多个问题,例如您打开文件 2 次,这是不必要的,其次您需要检查用户提供的用户名与所有用户名,不仅login_info[0]

你可以尝试类似的东西

username_password_map = {}

with open('user.txt') as f:
    for line in f.readlines():
        username, password = line.rstrip('\n').split(', ')
        username_password_map[username] = password


username = input("Please enter your username: ")
if username in username_password_map:
    while True:
        password = input("Please enter your password: ")
        if password == username_password_map[username]:
            print("Password correct!\n")
            print(f"Welcome {username}!\n")
            break
        else:
            print("Password incorrect.")
else:
    print("Username not found.")

推荐阅读