Access varaibles from csv file Python
Question: I have a python file that communicates with a device and access its
parameters. As I have to access more than 100 parameters, I have stored those
parameter names into one column in csv file. I want to access values assigned
to these parameters. But what I am getting the parameters names instead of its
values.

My csv file is like

    
    
    parameter1
    parameter2
    parameter3
    parameter4
    ...
    

I am using the following code:

    
    
    import csv
    TagList = []
    
    with open('parameters.csv', 'rb') as file:
        reader = csv.reader(file)
        for row in reader:
            TagList.append(row[0])
    
    for tag in TagList:
        print tag
    

Output:

    
    
    parameter1
    parameter2
    parameter3
    parameter4
    ...
    

What I want to access is the data assigned to these parameters. I can access
its value through its name. i.e.

    
    
    print parameter1
    output: 1.0
    

I have tried `print "%d" %(tag)`, that is also not working. Please help me in
that. Thanks in advance.


Answer: I'm not sure what the interface for your controller looks like, however I
think you would be looking to use reflection here.

so `TagList[0]` sounds like it is equal to `"parameter1"` at this point.

If you access your controller through a python class you'd be looking to do
something like `getattr(controller, TagList[0]`.

Here is a code example that shows how that would work:

    
    
    class foo(object):
        x = 3
    
    var = "x"
    print getattr(foo(), var)
    

EDIT:

Okay from what you are saying it sounds like it would be more like this:

    
    
    variable1 = 0
    variable2 = "true"
    
    paramList = ["variable1", "variable2"]
    for param in paramList:
        print eval(param)
    

The docstring for `eval()` is: Evaluate the source in the context of globals
and locals. So this should pick up those variables if they do not belong to an
instance.

Also see [How to get the value of a variable given its name in a
string?](http://stackoverflow.com/questions/9437726/how-to-get-the-value-of-a-
variable-given-its-name-in-a-string) which has an answer using
`globals()['a']` to narrow the scope of the evaluation.

