Python 配置文件的操作

来源:互联网 发布:淘宝上买到假货仅退款 编辑:程序博客网 时间:2024/06/09 20:32

读取配置文件的特定section和option

#!/usr/bin/python # -*- coding:UTF-8 -*-'''Created on 2015-4-30@author: huangpeng03'''import ConfigParser conf = ConfigParser.ConfigParser()conf.read('bsrom.cfg')host = conf.get('mysql', 'host')print host


写入特定section的option和value

#!/usr/bin/python # -*- coding:UTF-8 -*-'''Created on 2015-4-30@author: huangpeng03'''import ConfigParserconf = ConfigParser.ConfigParser()conf.add_section('newsection')conf.set('newsection', 'newoption', 'newvalue')f = open('bsrom.cfg','a+')conf.write(f)f.close()

修改

#!/usr/bin/python # -*- coding:UTF-8 -*-'''Created on 2015-4-30@author: huangpeng03'''import ConfigParserconf = ConfigParser.ConfigParser()conf.read('bsrom.cfg')conf.set('romkeyword', 'filepath', 'path2')f = open('bsrom.cfg','r+')      #注意修改是r+模式conf.write(f)f.close()


删除

#!/usr/bin/python # -*- coding:UTF-8 -*-'''Created on 2015-4-30@author: huangpeng03'''import ConfigParserconf = ConfigParser.ConfigParser()conf.read('bsrom.cfg')conf.remove_option('common', 'log_path')  #删除配置项conf.remove_section('beanstalkc')f = open('bsrom.cfg','w+')  #注意打开模式conf.write(f)f.close()



0 0