我想从.cnf文件中读取数据。它可能有很多部分,所以我想自动读出它们。我的代码如下:
while numberOfSections > 0:
check = parser.get(numberOfSections, "check")
hostname = parser.get(numberofSections, "hostname")
ip = parser.get(numberofSections, "IP")
port = parser.get(numberofSections, "port")
request = parser.get(numberofSections, "request")
现在不幸的是,它只说“无节:5”。在此示例中,我的numberofSections变量为5,仅此而已。这些部分的命名如下:
[1]
check = ''
hostname = ''
IP = ''
port = ''
request = ''
[2]
check = ''
hostname = ''
IP = ''
port = ''
request = ''
[3]
check = ''
hostname = ''
IP = ''
port = ''
request = ''
...
那么,有什么想法吗?我是python的新手,所以请慢慢解释。
答案 0 :(得分:3)
返回了异常No section: 5
,因为您使用的while
循环始终带有true
参数。
您应该使用for
循环,例如:
for section in config.sections():
check = parser.get(section, "check")
hostname = parser.get(section, "hostname")
ip = parser.get(section, "IP")
port = parser.get(section, "port")
request = parser.get(section, "request")