I have 15 values that I want to get from a config file and store them in separate variables.
I am using
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read(configFile)
and it is a really good library.
Option #1
If I change the name of the variable and want it to match the config file entry I have to edit the corresponding line in the function
def fromConfig():
#open file
localOne = parser.get(section, 'one')
localTwo = parser.get(section, 'two')
return one, two
one = ''
two = ''
#etc
one, two = fromConfig()
Option #2
It is cleaner to see where the variables get their values from, but then I would be opening and closing the file for every variable
def getValueFromConfigFile(option):
#open file
value = parser.get(section, option)
return value
one = getValueFromConfigFile("one")
two = getValueFromConfigFile("two")
Option #3
This one doesn't make much sense since I have to have another list of all my variable names, but the function is cleaner.
def getValuesFromConfigFile(options):
#open file
values = []
for option in options:
values.append(parser.get(section, option))
return values
one = ''
two = ''
configList = ["one", "two"]
one, two = getValuesFromConfigFile(configList)
EDIT: Here is my attempt at reading the file one and storing all values in a dict and then trying to use he values. I have a multi-lined string and I am using
%(nl)s to be a new line character so then when I get the value
message = parser.get(section, 'message', vars={'nl':'\n'})
Here is my code:
from ConfigParser import SafeConfigParser
def getValuesFromConfigFile(configFile):
''' reads a single section of a config file as a dict '''
parser = SafeConfigParser()
parser.read(configFile)
section = parser.sections()[0]
options = dict(parser.items(section))
return options
options = getValuesFromConfigFile(configFile)
one = options["one"]