Best way to retrieve variable values from a text file?
But what i'll love is to refer to the variable direclty, as i declared it in the python script..
Assuming you're happy to change your syntax slightly, just use python and import the "config" module.
# myconfig.py:var_a = 'home'var_b = 'car'var_c = 15.5
Then do
from myconfig import *
And you can reference them by name in your current context.
Use ConfigParser.
Your config:
[myvars]var_a: 'home'var_b: 'car'var_c: 15.5
Your python code:
import ConfigParserconfig = ConfigParser.ConfigParser()config.read("config.ini")var_a = config.get("myvars", "var_a")var_b = config.get("myvars", "var_b")var_c = config.get("myvars", "var_c")
You can treat your text file as a python module and load it dynamically using imp.load_source
:
import impimp.load_source( name, pathname[, file])
Example:
// mydata.txtvar1 = 'hi'var2 = 'how are you?'var3 = { 1:'elem1', 2:'elem2' }//...// In your script filedef getVarFromFile(filename): import imp f = open(filename) global data data = imp.load_source('data', '', f) f.close()# path to "config" filegetVarFromFile('c:/mydata.txt')print data.var1print data.var2print data.var3...