Setting properties from CSV file using eval (Python)
Question: I have CSV files that contain numerous values that I want to reference. I
wanted to parse them succinctly using `eval`. Here's what I tried:

    
    
    line = fileHandle.readline()
    while line != "":
      if line != "\n":
        parameter = line.split(',')[0]
        value = line.split(',')[2].replace("\n", "")
        eval("%s = \"%s\"" % (parameter, value))
        print(parameter + " = " + eval(parameter)) # a quick test
      line = fileHandle.readline()
    

What I get is:

    
    
    Traceback (innermost last):
      File "<string>", line 73, in ?
      File "<string>", line 70, in createJMSProviders
      File "<string>", line 49, in createJMSProviderFromFile
      File "<string>", line 1
        externalProviderURL="tibjmsnaming://..."
                           ^
    SyntaxError: invalid syntax
    

I reads to me like it is not possible to
`eval("externalProviderURL=\"tibjmsnaming://...\"")`. What is wrong with this
statement?


Answer: As per S.Lott's suggestion, here is how I would solve this issue. I might be
simplifying a little bit. If so, I apologize, but I haven't seen your data.

    
    
    import csv
    my_dict = {}
    with open('my/data.csv') as f:
        my_reader = csv.reader(f)
        for row in my_reader:
            my_dict[row[0]] = row[2]
    

As you can see, there are a number of differences from your code here. First
of all, I'm using Python's [`with` statement](http://effbot.org/zone/python-
with-statement.htm), which is a good habit to get into when working with
files. Second, I'm using python's
[`csv`](http://docs.python.org/library/csv.html) module to create a reader
object, which you can iterate over in a `for` loop. This is significantly more
pythonic than using a `while` loop. Finally, and probably most relevantly, I'm
adding these values to a dictionary, rather than trying to plop them into
variables in the global scope. To access these parameters, you can simply do
the following:

    
    
    my_dict['externalProviderURL']
    

However, you get a lot more than this. Storing your values in an actual data
structure will allow you use all of it's [built in
methods](http://docs.python.org/library/stdtypes.html#mapping-types-dict). For
example, you can go back and iterate over it's keys and values

    
    
    for key, value in my_dict.iteritems():
        print key 
        print value
    

Pythonic code often involves a significant use of dictionaries. They're finely
tuned for performance, and are made particularly useful since most anything
can be stored as a value in the dictionary (lists, other dictionaries,
functions, classes etc.)

