当前位置: 动力学知识库 > 问答 > 编程问答 >

Setting properties from CSV file using eval (Python)

问题描述:

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?

网友答案:

eval() is for evaluation Python expressions, and assignment (a = 1) is a statement. You'll want exec().

>>> exec("externalProviderURL=\"tibjmsnaming://...\"")
>>> externalProviderURL
'tibjmsnaming://...'

(FYI, to use eval() you'd have to do externalProviderURL=eval("\"tibjmsnaming://...\""), but it looks like your situation is more suited to exec).

网友答案:

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, which is a good habit to get into when working with files. Second, I'm using python's csv 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. 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.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: