How do I extract a row of a file in python?
Question: I have an rfid reader hooked up to a raspberry pi. When i scan a card, I get a
UID number stored in my python file as "backData" I would like to store all of
my users in a separate file (IE: csv or txt file), instead of at the top of my
code and then read that file to authenticate and extract the relevant row. My
current python code is as follows:

    
    
    user1 = [1,23,45,678,987]
    user2 = [9,87,65,432,123]
    
    if  backData == user1:
      f = open("/mnt/lock_logs/lock_log.csv", "a");
      print f
      value = ('\n' 'user1,FOB,') + (',') + time.strftime("%c")
      myString = str(value)
      f.write(myString)
      f.close()
      GPIO.digitalWrite(RELAY, GPIO.HIGH)
      GPIO.digitalWrite(LEDBLUE, GPIO.LOW)
      GPIO.digitalWrite(LEDGREEN, GPIO.HIGH)
      print "Access Granted"
      time.sleep(1)
      GPIO.digitalWrite(RELAY, GPIO.LOW)
      time.sleep(3)
      GPIO.digitalWrite(LEDGREEN, GPIO.LOW)
      GPIO.digitalWrite(LEDBLUE, GPIO.HIGH)
    

So Ideally, I would read a csv file, find the UID, and print the row to a log.
The csv file would look like this.

    
    
    [1,23,456,78,987], Full Name
    

Thanks in advance for reviewing my issue.


Answer: Something like the below will read the file into a dict in the script.

    
    
    import csv
    
    users = {}
    with open('users.csv', 'r') as fp:
        reader = csv.reader(fp)
        for row in reader:
           id = row[0][1:-1].split(',')
           name = row[1]
           users[id] = name
    

That will build you a dict of ids to names. But honestly why not just use json
and dump()/load() the file as a whole? Is it being used by some other program
or service? Your main difficulty is translational of a text representation to
a data representation, that what formats like json do, why not use them?

if it was json format it would be:

    
    
    import json
    
    users = {}
    with open('users.json', 'r') as fp:
       users = json.load(fp)
    

And it would be much less error prone than the assumption I made in the first
version. The resulting `users` would look like this once loaded:

    
    
    {
        [1,23,45,678,987]: 'name1', 
        [9,87,65,432,123]: 'name2'
    }
    

So to get the user would be:

    
    
    if users.get(backData, None) in ('name1', 'name2'):
        #stuff
    

of

    
    
    if users.get(backData, None) is not None:
        #stuff
    

json is just a serialization format. So whatever data structure you call
dump() on is what you'll get back when you call load(). Check out the
[docs](https://docs.python.org/2/library/json.html).

