Search code examples
pythonconfigparser

How to load all variables from a configparser file?


I am trying to load all variables defined in a text file using configparser. I have managed to load them using a dictionary but I would like them to be loaded directly as variables. Is there a clean way to do it?

###file.txt##########
[Section1]
var1 = 10.0
var2 = 25.0
####################

import configparser

cp = configparser.ConfigParser()   
configFilePath = r'file.txt'
cp.read(configFilePath)

d = dict(cp.items('Section1'))

for a in d:
    d[a]=float(d[a])

now I can get var1 as d['var1'] but I want to just be able to get it as a variable

I want to do the following:

print(var1)

#output ---> 10.

Solution

  • you can do something like:

    for a in d:
        exec("%s=%s" % (a,float(d[a])))
    

    Saying that, I won't recommend doing that, it will make your code very messy and hard to read and follow