【发布时间】:2013-02-04 21:09:08
【问题描述】:
我想从配置文件中获取 15 个值并将它们存储在单独的变量中。
我正在使用
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read(configFile)
这是一个非常好的图书馆。
选项#1
如果我更改变量的名称并希望它与配置文件条目匹配,我必须在函数中编辑相应的行
def fromConfig():
#open file
localOne = parser.get(section, 'one')
localTwo = parser.get(section, 'two')
return one, two
one = ''
two = ''
#etc
one, two = fromConfig()
选项 #2
查看变量从何处获取值更清晰,但随后我将为每个变量打开和关闭文件
def getValueFromConfigFile(option):
#open file
value = parser.get(section, option)
return value
one = getValueFromConfigFile("one")
two = getValueFromConfigFile("two")
选项#3
这个没有多大意义,因为我必须有一个包含所有变量名的列表,但函数更简洁。
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)
编辑: 这是我尝试读取文件并将所有值存储在字典中然后尝试使用他的值。 我有一个多行字符串,我正在使用
%(nl)s to be a new line character so then when I get the value
message = parser.get(section, 'message', vars={'nl':'\n'})
这是我的代码:
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"]
【问题讨论】:
-
为什么它同时标记为 python-3.x 和 python-2.7?您是否需要编写同时适用于两者的代码?
标签: python python-3.x python-2.7 configparser