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"))
Python模块之: ConfigParser
最新推荐文章于 2024-03-20 18:30:18 发布