Search code examples
pythondictionaryraspberry-pirfid

Why is my Python Dictionary only returning the last value?


I have an rfid reader which when scanned returns a UID as "backData"

I have my users (username and UID) stored in a text file.

I've managed to read the text file into a python dictionary, but when i scan my card, it is only accepting the last UID in the text file.

Text File:

164 168 124 90 42, user1
114 156 203 196 225, user2

Python Code:

for line in uid_file:
    info = line.split(",")
    key = info[0]
    uname = info[1]
    c = len(uname)-1
    uname = uname[0:c]
    uid_dict[key] = uname
    USER = [int(i) for i in key.split()]

    if backData == USER:
        f = open("/mnt/lock_logs/lock_log.csv", "a");
        print f
        value = ('\n') + uname
        myString = str(value)
        f.write(myString)
        f.close()
     else:
        print "Access Denied"

So if I scan the card assigned to user2, it works, but if I scan the card assigned to user1, I get Access Denied.

If i print the variable USER, it returns both UIDs from the text file. Any ideas on what I need to change??


Solution

  • I think this is because you continue to evaluate your for loop even after the user 1 is matched. Add a 'break' to the bottom of your if statement.

    if backData == USER:
        f = open("/mnt/lock_logs/lock_log.csv", "a");
        print f
        value = ('\n') + uname
        myString = str(value)
        f.write(myString)
        f.close()
        break
    

    I recreated your file and am able to get predicted behavior with the following code. Not that I hard coded backData and have tried it with both USER lists with success.

    filename = 'uid.txt'
    
    with open(filename) as uid_file:
        uid_dict={}
    
        backData = [164, 168, 124, 90, 42]
        no_matches = True
    
        for line in uid_file:
            info = line.split(",")
            key = info[0]
            uname = info[1]
            print info[0], info[1]
            c = len(uname)-1
            uname = uname[0:c]
            uid_dict[key] = uname
            USER = [int(i) for i in key.split()]
    
            if backData == USER:
                print "user matches"
                no_matches = False          
                break
    
        if no_matches:
            print "Access Denied"