Home > Software design >  Why doesn't my program properly read from my text file?
Why doesn't my program properly read from my text file?

Time:11-28

I made a text file with a list of usernames and passwords. My program (in a tkinter page) is supposed to check whether the username and password exists in the file, and then if it doesn't it makes a label that says 'username or password incorrectenter image description here'. However, even when the username and password clealy exists in the text file, it will still print the 'incorrect' message. Here's an example of something in my text file:

testusername.testpassword

And here is the code that's supposed to detect it:

def login_incorrect():
    Label(loginPage, text="Username or password incorrect.").place(x=120, y=120)
    # print("def login incorrect")
def LoginToAccount():
    print("def login to account")
    # while True:  # This loop will run as long as the user is not logged in.
    with open('AccountDatabase.txt'):
        if loginUsernameE.get()   '.'   loginPasswordE.get() not in open('AccountDatabase.txt').read():
            login_incorrect()
            print('incorrect')
            print(loginUsernameE.get()   '.'   loginPasswordE.get())

But when I write testusername in the username field and testpassword in the password field, it still shows the error. Here's a screenshot:

Why can't I detect if text is in a text file?

CodePudding user response:

Try this code. I fixed opening the file for read and the condition.

def login_incorrect():
    Label(loginPage, text="Username or password incorrect.").place(x=120, y=120)
    # print("def login incorrect")
def LoginToAccount():
    print("def login to account")
    # while True:  # This loop will run as long as the user is not logged in.
    with open('AccountDatabase.txt', 'r') as f:

        if loginUsernameE.get()   '.'   loginPasswordE.get() not in f.read():
            login_incorrect()
            print('incorrect')
            print(loginUsernameE.get()   '.'   loginPasswordE.get())

CodePudding user response:

It looks like you first need to read the file, and only then check for the occurrence of the desired one.

with open('AccountDatabase.txt', 'r') as f:
    file_logins = f.read()
    if loginUsernameE.get()   '.'   loginPasswordE.get() not in file_logins:
        login_incorrect()
        print('incorrect')
  • Related