user5272899
user5272899

Reputation:

Iterating through a text file to find a username and password match in Python

The structure of the for loop looks wrong. For some reason it isn't correctly jumping to the 'else' part of the statement. I'm going to try this in the console to simplify things a little and see if I have any luck:

def verifylogin():
fin=open("moosebook.txt","r")
data=fin.readlines()
for line in data:
    fields=line.split()
    fields=[i.rstrip("','") for i in fields] #strips the named character from END of field
    fields=[i.replace("'",'') for i in fields]#when reading the list, you want to remoe the ',' so it isn't part of the username or password
    fields=[i.replace("(",'') for i in fields] #simiarly, remove the bracket and replace it
    line=line.rstrip()
    print(fields)

    access_permitted = False
    for counter in range(0,len(fields)):
        if textlogin.get()==fields[counter] and textpassword.get()==fields[counter+1]:
            access_permitted=True
            if access_permitted:
                    welcome=Label(myGui,text="Access Granted. Loading Profile ....")
                    welcome.pack()

        else:
                    denied=Label(myGui,text="Access Denied")
                    denied.pack()

Upvotes: 2

Views: 1225

Answers (1)

Kevin
Kevin

Reputation: 76264

The way your loop is structured, you'll get the "denied" message for every line in the file that doesn't match your username/password, and get the "accepted" message for every line that does match. If you only want to show exactly one message, then wait until the loop ends to create one.

access_permitted = False
for i,s in enumerate(fields):
    if textlogin.get()==fields[i] and textpassword.get()==fields[i+1]:
        access_permitted = True

if access_permitted:
    welcome=Label(myGui,text="Access Granted. Loading Profile ....")
    welcome.pack()
else:
    denied=Label(myGui,text="Access Denied")
    denied.pack()
    line=fin.readline()

I can't say for sure, but it also seems likely that you're going to get an IndexError: list index out of range error in the loop, because fields[i+1] goes one past the end of the list on the final iteration. I'm guessing that fields is a list containing username + password tuples, in which case you should try:

for username, password in fields:
    if textlogin.get()==username and textpassword.get()==password:
        access_permitted = True

If fields isn't a username-password tuple list, you will probably need to try something else.


If each item in fields contains a user name and password and also other items, try:

for row in fields:
    if textlogin.get()==row[0] and textpassword.get()==row[1]:
        access_permitted = True

Upvotes: 1

Related Questions