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_b: 'car'
var_c: 15.5
And i need that python read the file and then create a variable named var_a with value 'home', and so on.
Example:
#python stuff over here
getVarFromFile(filename) #this is the function that im lookin for
print var_b
#output: car, as string
print var_c
#output 15.5, as number.
Is this possible, i mean, even keep the var type?
Notice that i have the full freedom to the text file structure, i can use the format i like if the one i proposed isn't the best.
EDIT: the ConfigParser can be a solution, but i dont like it so much, becose in my script i'll have then to refer to the variables in the file with
config.get("set", "var_name")
But what i'll love is to refer to the variable direclty, as i declared it in the python script..
There is a way to impoer the file as a python dictionary?
Oh, last thing, keep in mind that i dont know exactly how many variables would i have in the text file
Edit 2: i'm very interessing to the stephan json solution, becose in that way the text file could be readed simply with others languages (php, then via ajax javascript, for example), but i fail in something while acting that solution:
#for the example, i dont load the file but create a var with the supposed file content
file_content = "'var_a': 4, 'var_b': 'a string'"
mydict = dict(file_content)
#Error: ValueError: dictionary update sequence element #0 has length 1; 2 is required
file_content_2 = "{'var_a': 4, 'var_b': 'a string'}"
mydict_2 = dict(json.dump(file_content_2, True))
#Error:
#Traceback (most recent call last):
#File "<pyshell#5>", line 1, in <module>
#mydict_2 = dict(json.dump(file_content_2, True))
#File "C:\Python26\lib\json\__init__.py", line 181, in dump
#fp.write(chunk)
#AttributeError: 'bool' object has no attribute 'write'
In what kind of issues can i fall with the Json format? And, how can i read a json array in a text file, and transform it in a python dict?
p.s: i dont like the solution using .py files, i'll prefer .txt, .inc, .whatever is not restrictive to one language