简体   繁体   中英

How do I loop my password/username login page and read the password/username from an external file?

I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.

As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.

My code:

print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
    userInput = input("Password?\n")   
    if userInput == password:
       print("Welcome!")
       print('\n--------------------------------------------------------\n')
       print ("BTN = 0.10")
       print ("= £315.37")
    else:
       print("That is the wrong password.")
else:
    print("That is the wrong username.")
print('\n--------------------------------------------------------\n')

do something like this:

password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
    print("incorrect")
    theirUsername = input("What is your username")
    theirPassword = input("What is your password")
print("correct")



You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as

username
password

do text = text.split("\\n") and then username = text[0] and password = text[1]

this is what it should look like with an explanation:

file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
    print("incorrect") #notifies them of being wrong
    theirUsername = input("What is your username") #gets new username input
    theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct

So you want to loop it. Where would a good place for that be? How about when we ask for a question.

Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.

print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
    userInput = input("What is your username?\n")
    if userInput == username:
        userInput = input("Password?\n")
        if userInput == password:
            break
        else:
            print("That is the wrong password.")
    else:
        print("That is the wrong username.")

print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")

Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.

Now create a proper function.

def read_credentials_from_file(filename):
    """Read the file and return (username, password).
    File contents are first line username and second line password.
    """
    # Using the `with` statement is current best practice.
    with open(filepath, "rt") as user:
        username = user.readline().strip()
        password = user.readline().strip()
    return username, password

Now fix your code to use the function.

username, password = read_credentials_from_file(...)

Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.

Let's say your text file (credentials.txt) reads:

Janupedia
12345

Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.

print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
    array = []
    for line in f:
        array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
    userInput = input("Username?")
    if username.strip(' \n') == userInput.strip(' \n'):
        userInput = input("Password?")  
        if password.strip(' \n') == userInput.strip(' \n'):
            login = 1 #login successful set login status to 1 thus breaking loop 
        else:
            print("Incorrect")
    else:
        print("Incorrect")
        print('\n--------------------------------------------------------\n')
#  Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM