Python 配置文件的操作

配置文件操作指南
本文介绍如何使用Python的ConfigParser模块来操作配置文件。包括读取特定section和option、写入新的section与option、修改现有option的值以及删除指定的section或option。

读取配置文件的特定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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值