python – Best way to retrieve variable values from a text file?

python – Best way to retrieve variable values from a text file?

But what ill love is to refer to the variable direclty, as i declared it in the python script..

Assuming youre 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 ConfigParser

config = 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)

python – Best way to retrieve variable values from a text file?

You can treat your text file as a python module and load it dynamically using imp.load_source:

import imp
imp.load_source( name, pathname[, file]) 

Example:

// mydata.txt
var1 = hi
var2 = how are you?
var3 = { 1:elem1, 2:elem2 }
//...

// In your script file
def getVarFromFile(filename):
    import imp
    f = open(filename)
    global data
    data = imp.load_source(data, , f)
    f.close()

# path to config file
getVarFromFile(c:/mydata.txt)
print data.var1
print data.var2
print data.var3
...

Leave a Reply

Your email address will not be published.