您的位置:首页 > 编程语言 > Python开发

Python 配置文件的操作

2015-04-30 14:41 465 查看
读取配置文件的特定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 ConfigParser
conf = 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 ConfigParser
conf = 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 ConfigParser
conf = 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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: