利用configparser生成和读取配置文件

#Author by Andy
#_*_ coding:utf-8 _*_
import configparser
'''
配置文件格式
groupname:
item_key1=value
item_key2=value
'''
def create_config():
'''生成配置文件'''
cf = configparser.ConfigParser()
i = 1
groupname = ['group1','group2','group3','group4']
for g in groupname:
# cf.add_section('groupname') 添加组名
cf.add_section(g)
for i in range(10):
# cf.set('groupname','item_key','value') #在已有组名下添加item和value信息
cf.set(g,'ip%s'%i,'10.1.2.'+str((1+i)))
cf.set(g,'host%s'%i,'host%s'%i)
cf.write(open('config','w'))#写入配置文件 def read_config():
''' 读取配置文件'''
cf = configparser.ConfigParser()
# read config
cf.read("config")
sec =cf.sections() #groupname list
print(sec)
# ['group1', 'group2', 'group3', 'group4']
opts = cf.options('group1')#item_key list
print(opts)
# ['ip0', 'host0', 'ip1', 'host1', 'ip2', 'host2', 'ip3', 'host3', 'ip4', 'host4', 'ip5', 'host5', 'ip6', 'host6',
# 'ip7', 'host7', 'ip8', 'host8', 'ip9', 'host9']
kvs = cf.items('group1') #返回由item_key,value元组所构成的列表[(item_key,value)]
print(kvs)
# [('ip0', '10.1.2.1'), ('host0', 'host0'), ('ip1', '10.1.2.2'), ('host1', 'host1'), ('ip2', '10.1.2.3'),
# ('host2', 'host2'), ('ip3', '10.1.2.4'), ('host3', 'host3'),]
read_config()

配置文件格式

[group1]
ip0 = 10.1.2.1
host0 = host0
ip1 = 10.1.2.2
host1 = host1 [group2]
ip0 = 10.1.2.1
host0 = host0
ip1 = 10.1.2.2
host1 = host1
05-23 17:33