python - 如何将多行文本文件分解为一个可以迭代的列表以检查 python 中的输入 == 文本文件?
问题描述
运行代码时,我得到一个逻辑错误,它继续抛出第一个 if 语句错误“错误!用户名不存在”。我需要能够以管理员身份登录,然后通过将用户添加到 .txt 文件来添加用户,之后,如果再次运行程序,我可以通过管理员或在 txt 中创建的新用户之一登录文件。我似乎无法正确拆分它,以便在登录时循环正确地遍历列表。
例子:
print(new_lines) = [['admin', 'adm1n'], ['kevin', 'kev1n'], ['dorothy', '1234']]
.txt 文件内容,每个条目都在新行 = admin,adm1n\n kevin,kev1n\n dorothy,1234
到目前为止的代码:
import time
#User input of username and password
user_name = input("Username:\n")
user_pass = input("Password: \n")
#Opening document
with open("user.txt", "r+", encoding = "utf-8-sig") as f:
new_lines = []
for line in f:
new_line = line.strip()
new_lines.append(new_line.split(","))
print(new_lines)
#Loop to enter user name and password
for x in new_lines:
for y in x:
if user_name != new_lines[:][0]:
print("Error! Username does not exist.")
user_name = input("Username:\n")
user_pass = input("Password: \n")
elif user_pass != new_lines[:][1]:
print("Error! Incorrect password.")
user_name = input("Username:\n")
user_pass = input("Password: \n")
else:
print("Welcome back!")
break
break
#User options to choose from
user_choice = input("""\nPlease select one of the following options:
\nr - register user
\na - add task
\nva - view all tasks
\nvm - view my tasks
\ne - exit
\nAnswer: """)
解决方案
我建议稍微重新格式化代码,以便更容易找到用户名是否存在以及密码是否正确。
import time
#User input of username and password
user_name = input("Username:\n")
user_pass = input("Password: \n")
#Opening document
with open("user.txt", "r+", encoding = "utf-8-sig") as f:
new_lines = []
for line in f:
new_line = line.strip()
new_lines.append(new_line.split(","))
usernames = [acc[0] for acc in new_lines]
pws = [acc[1] for acc in new_lines]
while True:
if user_name not in usernames:
print("Error! Username does not exist.")
user_name = input("Username:\n")
user_pass = input("Password: \n")
else:
pw_index = usernames.index(user_name)
if user_pass != pws[pw_index]:
print("Error! Incorrect password.")
user_name = input("Username:\n")
user_pass = input("Password: \n")
else:
print("Welcome back!")
break
#User options to choose from
user_choice = input("""\nPlease select one of the following options:
\nr - register user
\na - add task
\nva - view all tasks
\nvm - view my tasks
\ne - exit
\nAnswer: """)
推荐阅读
- python - 如何使用 pandas 编辑 XLSX 电子表格
- javascript - 使用 vanilla javascript 隐藏包含某些文本的标签
- java - SpringData MongoDB Repositories 查询嵌套对象中的多个字段
- java - 如何使我的过滤器模式更通用
- jspm - 为什么 JSPM 不捆绑捆绑模块的依赖关系?
- excel - 在没有VBA的情况下更新excel中的动态下拉列表
- unity3d - Unity2D 中的照明在手机上看起来与在编辑器中不同
- dataset - 使用带有多个 aeneas 文本文件的 Aeneas 强制对齐
- php - 无法使用 Codeigniter 更新我的数据库
- javascript - 将数字四舍五入到最接近的“平滑”数字的功能