Python标准库之ConfigParser模块
ConfigParser模块用于生成和修改常见配置文档。
比如配置文件格式如下:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
生成一个配置文件
import configparser
cfp = configparser.ConfigParser()
cfp['DEFAULT'] = {'ServerAliveInterval':'45','Compression':'yes','CompressionLevel':'9','ForwardX11':'yes'}
cfp['bitbucket.org'] = {'User':'hg'}
cfp['topsecret.server.com'] = {'Port':'50022','ForwardX11':'no'}
with open("test.ini",'w') as confile:
cfp.write(confile)
运行后,在当前目录下生成了一个test.ini文件,文件内容如下:

读配置文件
defaults返回的是元组类型。
import configparser
cfp = configparser.ConfigParser()
cfp.read("test.ini")
print(cfp.defaults())
print(cfp.sections())
print(cfp['bitbucket.org']['user'])
运行结果如下:

遍历读取
import configparser
cfp = configparser.ConfigParser()
cfp.read("test.ini")
for i in cfp.defaults():
print(i,cfp.defaults()[i])
运行结果:

增删
删section
cfp.read("test.ini")
sec = cfp.remove_section('bitbucket.org')
cfp.write(open('test.ini', "w"))
删option:
cfp.read("test.ini")
sec = cfp.remove_option('topsecret.server.com','port')
cfp.write(open('test.ini', "w"))
增section:
cfp.read("test.ini")
sec = cfp.add_section('xxxx.server.com')
cfp.write(open('test.ini', "w"))
增option:
cfp.read("test.ini")
sec = cfp.set('topsecret.server.com','port',"5002")
cfp.write(open('test.ini', "w"))

浙公网安备 33010602011771号