configparser主要用于生成和修改常见配置文档,所以常见的操作为读和写
1.写
定义参数变量,赋值
- 直接赋值法
conf['test_default']={'test_line1':'test_line1'}
- 通过增加section ,set赋值法
conf.add_section('test')
conf.set('test','test_line1','test_line1')
- 通过增加section.option赋值法
conf.add_section('test1')
x=conf['test1']
x['test_line1']='test_line1'
- 通过空字典赋值法
conf['test2']={}
conf['test2']['test_line1']='test_line1'
1 #!/usr/bin/python 2 import configparser 3 4 conf=configparser.ConfigParser() 5 #新增,写入 6 #方式一 7 conf['test_default']={'test_line1':'test_line1', 8 'test_line2':'test_line2', 9 'test_line3':'test_line3', 10 'test_line4':'test_line4'} 11 12 #方式二,先新增一个section,再设置配置属性 13 conf.add_section('test') 14 conf.set('test','test_line1','test_line1') 15 conf.set('test','test_line2','test_line2') 16 conf.set('test','test_line3','test_line3') 17 conf.set('test','test_line4','test_line4') 18 19 conf.add_section('test1') 20 x=conf['test1'] 21 x['test_line1']='test_line1' 22 x['test_line2']='test_line2' 23 x['test_line3']='test_line3' 24 x['test_line4']='test_line4' 25 26 27 28 conf['test2']={} 29 conf['test2']['test_line1']='test_line1' 30 conf['test2']['test_line2']='test_line2' 31 conf['test2']['test_line3']='test_line3' 32 conf['test2']['test_line4']='test_line4'View Code
写入文件
将conf变量里面的值存入文件中,打开文件,执行写操作
1 #!/usr/bin/python 2 import configparser 3 4 conf=configparser.ConfigParser() 5 conf['test_default']={'test_line1':'test_line1', 6 'test_line2':'test_line2', 7 'test_line3':'test_line3', 8 'test_line4':'test_line4'} 9 #写入 10 with open('conf_test','w',encoding='utf-8') as f: 11 conf.write(f)View Code
2.读
从变量里面读
1 #!/usr/bin/python 2 import configparser 3 4 conf=configparser.ConfigParser() 5 6 print(conf.read('conf_test')) 7 8 print(conf.sections())#读所有section 9 print(conf.options('test')) 10 print('test5' in conf) #section是否存在 11 print(conf['test2']['test_line1'])#读取sectiontest2中port属性的值 12 print(conf.items('test2'))#将配置key-value读出,可以通过dict转为字典View Code
从文件里面读
1 #!/usr/bin/python 2 import configparser 3 4 conf=configparser.ConfigParser() 5 conf.read('conf_test')#从文件里面读View Code
3.移除
1 #!/usr/bin/python 2 import configparser 3 4 conf=configparser.ConfigParser() 5 print(conf.has_option(section='test',option='test_line1'))#是否有这个配置 6 conf.remove_option(section='test',option='test_line1')#删除这个属性配置 7 conf.remove_section('test')View Code
标签:常用,python,section,line4,line1,conf,test,configparser From: https://www.cnblogs.com/Little-Girl/p/17995101