Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't compare input variables to those from a file

I am making a login system for my project, and I have the usernames and passwords stored in a text file, with usernames in the first column and passwords in the second column, and then separating each login/password with a new line and using : as a barrier between the username/password.

Upon entering the correct username and password, I always get incorrect login, however if I only compare the username to the file it functions properly. Even if I print the password and username straight from the file and then print it next to the username/password I entered, it is still the exact same yet still say incorrect login!

def login():
file=open("user.txt","r")
user=input("enter usename")
password=input("enter password") 
Check=False
for line in file:
    correct=line.split(":")
    if user==correct[0] and password==correct[1]:
        Check=True
        break
if Check==True:
    print("succesffuly logged in")
    file.close()
    mainMenu()
else:
    print("incorrect log in")
    file.close()
    login()
like image 223
sean Avatar asked Mar 28 '18 15:03

sean


1 Answers

I suspect you have a \n at the end of each user / password string. I suspect line looks like user:pass\n after being read in. Use line.strip().split(':') to remove the newline, which is causing password==correct[1] to fail.

Replace:

for line in file:
    correct=line.split(":")

With:

for line in file:
    correct=line.strip().split(":")

For why, see https://docs.python.org/2/library/string.html#string.strip

string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

like image 71
Drise Avatar answered Sep 24 '22 20:09

Drise