-1
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")

I want to validate that a username and a password are stored in the file when the user tries to log in to the system and if they aren't, then return the user to then re-enter their login details and try again.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Read the Python docs about the `re` module and about the `for` compound statement and ask if you don't understand something specific. – Michael Butscher Nov 25 '17 at 23:56

1 Answers1

0

It sounds like you might want to wrap up your login request into a separate function. You can then call that function any time you want to prompt the user for their login details, including for repeated calls due to wrong input. A rough example:

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

About the "with open...": It works like your file = open, but has the advantage that the file.close is implied. So you don't have to do "file.closed" (which your snippet is missing) before returning from LoginPrompt.

I'm not actually familiar with re, so I assumed above that your code works for finding the user name. Depending on how your file is formatted, you could also ty something like this:

with open('up.txt', 'r') as file:
    for line in file.readlines:
        if ausername and apassword in line:
            return True
        ...
ikom
  • 166
  • 6