python - 在文件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
其中每一行都有用户名作为第一个字符串,后跟逗号,然后是密码。
如果有人可以帮助我或为我指出正确的方向以寻求答案。
解决方案
您的代码存在多个问题,例如您打开文件 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.")
推荐阅读
- right-to-left - 如何使 vtiger CRM RTL(从右到左)改变阿拉伯语等语言?
- tomcat - Web 服务器抛出错误,但应用程序继续运行
- jenkins - 安装在 AWS EKS 集群中的 Jenkins 中所做的任何配置更改都会在 30 分钟内消失
- sql - 使用 SQL 查询查找删除、添加和存在的票证数量
- oracle - 为什么此查询显示错误 ORA-00923: FROM keyword not found where expected?
- javascript - 需要一个匹配所有元素的正则表达式
@someText - reactjs - 在 react react-leaflet 中编译失败
- r - 在 rsm 包中使用 persp() 时,“轮廓”不是图形参数
- bash - 包装外壳内置程序
- windows - 文件夹上的这个剑标志是什么意思?