Python模块之: ConfigParser

1,扩展ConfigParser支持Key的大小写区分: 1234567891011121314 # -*- coding: UTF-8 -*- """ 继承自 ConfigParser ,区分大小写. """import ConfigParser class CappConfig(ConfigParser.ConfigParser): def __init__(self,filename): ConfigParser.ConfigParser.__init__(self) self.filename=filename self.read(filename) def optionxform(self,optionstr): return optionstr 2,以下面的test.ini配置文件为例: 123 [global] SN = teststr SRV = 192.168.1.1 3, 读取test.ini参数: 1234567 def read_ini(): cf = CappConfig("./test.ini") values = cf.get("global","SN") print values items = cf.items("global") print items print dict(items) 执行上面函数,程序输出: 123 teststr [('SN', 'teststr'), ('PTSRV', '192.168.1.1')] {'SN': 'teststr', 'PTSRV': '192.168.1.1'} 4,添加新参数: 12345678 def add_ini(): cf = CappConfig("./test.ini") cf.add_section("MySQL") cf.set("MySQL", "dbname", "db_name") cf.set("MySQL", "dbuser", "db_user") # write to file cf.write(open('./test.ini', "w")) 如果执行了上面的函数,那么test.ini的内容将为: 1234567 [global] SN = teststr PTSRV = 192.168.1.1 [MySQL] dbuser = db_user dbname = db_name 5,修改已经存在的参数: 1234 def modify_ini(): cf = CappConfig("./test.ini") cf.set("global", "SN", "TestValues") cf.write(open('./test.ini', "w")) 执行该函数后test.ini文件内容如下: 1234567 [global] SN = TestValues PTSRV = 192.168.1.1 [MySQL] dbname = db_name dbuser = db_user 你会发现global下面的SN的值已经发送改变. 6, 删除参数: 123456 def del_ini(): cf = CappConfig("./test.ini") #cf.remove_option("MySQL","dbuser") #cf.remove_option("MySQL","dbname") cf.remove_section("MySQL") cf.write(open('./test.ini', "w")) 如果执行上面的函数后test.ini将变为: 123 [global] SN = TestValues PTSRV = 192.168.1.1 7,完整文件: 1234567891011121314151617181920212223242526272829 # -*- coding: UTF-8 -*- from CappConfig import CappConfig # READ def read_ini(): cf = CappConfig("./test.ini") values = cf.get("global","SN") print values items = cf.items("global") print items print dict(items) def add_ini(): cf = CappConfig("./test.ini") cf.add_section("MySQL") cf.set("MySQL", "dbname", "db_name") cf.set("MySQL", "dbuser", "db_user") # write to file cf.write(open('./test.ini', "w")) def modify_ini(): cf = CappConfig("./test.ini") cf.set("global", "SN", "TestValues") cf.write(open('./test.ini', "w")) def del_ini(): cf = CappConfig("./test.ini") #cf.remove_option("MySQL","dbuser") #cf.remove_option("MySQL","dbname") cf.remove_section("MySQL") cf.write(open('./test.ini', "w"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值