Search code examples
pythonindexoutofboundsexception

Python giving list out of bounds but it shows both elements in the list


I'm trying to make a simple log in program using python (still fairly new to it), and I have the log in information stored in a text file for the user to match in order to successfully log in. Whenever I run it it says "list index out of range" but I'm able to print out the value of that element in the list, which is where I'm confused. I am trying to add the first line (username) and the second line (password) in the file to the list to compare to the user inputted values for each field, but am unable to compare them.

def main():
    username = getUsername()
    password = getPassword()
    authenticateUser(username, password)


def getUsername():
    username = input("Please enter your username: ")

    return username


def getPassword():
    password = input("Please enter your password: ")

    return password


def authenticateUser(username, password):
    credentials = []
    with open("account_information.txt") as f:
        content = f.read()
        credentials.append(content)

    if(username == credentials[0] and password == credentials[1]):
        print("Login Successful!")

    else:
        print("Login Failed")



main()

Solution

  • You should use readline to get your infos in a list :

    def authenticateUser(username, password):
        credentials = []
        with open("account_information.txt") as f:
            content = f.readlines()
    

    Using this, accordingly to what you describe, content[0] will be your username and content[1] your password.