Referring on this question, I have a similar -but not the same- problem..
On my way, I\'ll have some text file, structured like:
var_a: \'home\'
var_
Suppose that you have a file Called "test.txt" with:
a=1.251
b=2.65415
c=3.54
d=549.5645
e=4684.65489
And you want to find a variable (a,b,c,d or e):
ffile=open('test.txt','r').read()
variable=raw_input('Wich is the variable you are looking for?\n')
ini=ffile.find(variable)+(len(variable)+1)
rest=ffile[ini:]
search_enter=rest.find('\n')
number=float(rest[:search_enter])
print "value:",number
hbn's answer won't work out of the box if the file to load is in a subdirectory or is named with dashes.
In such a case you may consider this alternative :
exec open(myconfig.py).read()
Or the simpler but deprecated in python3 :
execfile(myconfig.py)
I guess Stephan202's warning applies to both options, though, and maybe the loop on lines is safer.
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
...
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")
How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.
As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.
(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).
def read_config(filename):
f = open(filename)
config_dict = {}
for lines in f:
items = lines.split(': ', 1)
config_dict[items[0]] = eval(items[1])
return config_dict
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.