Home > database >  Login System using a text file
Login System using a text file

Time:01-17

I am a beginner and i'm having trouble creating a login system, every time when i enter the right password and username it shows incorrect. Someone please help me with it. It must use a text file and try not to use functions please.

while True:
    f = open("password.txt", mode="r")
    data = f.readline()
    username = input("Please enter your username: ")
    password = input("Please enter your password: ")
    data2 = username ',' password
    if (data == data2):
        print("Logged in successfully as" username)
        break
    else:
        print('Incorrect')

CodePudding user response:

# you don't have to close the file using this approach
with open("password.txt", mode="r") as f:
    username = input("Please enter your username: ")
    password = input("Please enter your password: ")
    data = username ',' password
    # set a parameter to flag if uname,pass is found
    success = False
    # reading each line from the file
    for line in f.readlines():
        # compare the line with newline removed to input
        if line.strip() == data:
            success = True
            break
    if success:
        print("Logged in successfully as " username)
    else:
        print("Incorrect")

You were only reading the first line (I assume there is more than one user and this each user is on a line.) You also need to strip the newline char \n in order to successfully match the input.

CodePudding user response:

If there are more than one line in your passwords.txt file, f.readline() will return an additional \n at the end and this will make your comparison false. As @Keith mentioned, you can use strip function to fix that.

Otherwise you can add print statements to your code to see what's wrong:

f = open("password.txt", mode="r")
data = f.readline()
f.close()
print('Expected:', data)

while True:
    username = input("Please enter your username: ")
    password = input("Please enter your password: ")
    data2 = username ',' password
    print('User input:', data2)
    if (data == data2):
        print("Logged in successfully as" username)
        break
    else:
        print('Incorrect')

As you may have noticed I also moved file reading code out of the loop. You don't have to do that every time. I also used f.close() after we are done with the file so it is not locked.

CodePudding user response:

I may be completely overlooking a simple syntax error but I see nothing wrong with this code. If it's returning your incorrect statement you might want to add two print statements that print what the user inputted and what it's being compared to so you can see if there's a space being added or something. The print statements should look something like this and I'd place them above the if statement:

print(data)
print(data2)
  •  Tags:  
  • Related