Search code examples
pythonauthenticationreadfilewritefile

Why is it saying access denied when I input the username correctly?


Hey I have wrote this code however I cannot see what is wrong with it, it is saying that the username is wrong yet if I print it, it returns exactly what i input.

ea = input("Do you already have an account")
if ea == "Yes" or ea == "yes":
    Ausername = input("Input your username")
    Apassword = input("Input your password")

    f=open("login.txt","r")
    lines=f.readlines()
    username=lines[0]

    if (Ausername) == (username):
        print("Welcome to the quiz")
    else:
        print("Access denied")

    f.close()

else:
    name = input("Input your name")

    yeargroup = input("Input your year group")

    age = str(input("Input your age"))

    firstusername = ((name[0]+name[1]+name[2])+(age))
    print((firstusername)+(" is your username"))
    firstpassword = input("Enter what you want your password to be")
    print(firstusername)
    print(firstpassword)


    login = open("login.txt","a")
    login.write(firstusername + "\n" + name + "\n" + yeargroup + "\n" + age + "\n" + firstpassword + "\n")
    login.close()

print("---------------------------------------------------")

Solution

  • File data is read in by default with the trailing newline. Did you try calling str.strip before comparing your strings?

    if Ausername == username.strip():
        ...
    

    Also, if you want to do case insensitive comparisons, you should convert your string to lowercase using str.lower to reduce the size of your search space:

    if ea.lower() == "yes":
        ...