if login == "y":
ausername = input("Please enter username")
apassword = input("please enter your password")
file = open("up.txt", "r")
for line in file.readlines():
if re.search("ausername"+"apassword")
我想验证用户尝试登录系统时是否存储了用户名和密码,如果不是,则返回用户,然后重新输入登录详细信息并重试
答案 0 :(得分:0)
听起来您可能想要将登录请求包装到单独的函数中。然后,您可以在任何时候提示用户输入其登录详细信息时调用该功能,包括由于错误输入而重复调用。一个粗略的例子:
def SomeMainFunction(...):
# Everything else you're doing, then login prompt:
if login == 'y':
success = False
while not success:
success = LoginPrompt()
# While login is unsuccessful the loop keeps prompting again
# You might want to add other escapes from this loop.
def LoginPrompt():
ausername = input("Please enter username")
apassword = input("please enter your password")
with open("up.txt", "r") as file:
for line in file.readlines():
if re.search("ausername"+"apassword"):
# return True if login was successful
return True
else:
return False
关于“with open ...”:它的工作方式类似于你的文件= open,但其优点是暗示了file.close。因此,在从LoginPrompt返回之前,您不必执行“file.closed”(您的代码段丢失)。
我实际上并不熟悉re,所以我假设您的代码适用于查找用户名。根据文件的格式化方式,你也可以这样:
with open('up.txt', 'r') as file:
for line in file.readlines:
if ausername and apassword in line:
return True
...