python 配置文件类库_基础类封装-configparser配置文件类库封装

1 #!/usr/bin/env python3

2 #-*- coding: utf-8 -*-

3 #@Time : 2019/10/14 23:37

4 #@Author : Tang Yiwei

5 #@Email : 892398433@qq.com

6 #@File : ParseConfigurationFile.py

7 #@Software: PyCharm

8

9

10 from configparser importConfigParser11

12

13 classParseConfigFile():14

15 def __init__(self,configFilePath=None):16 self.cf =ConfigParser()17 try:18 if configFilePath isNone:19 raise FileNotFoundError("Can't found config file!")20 else:21 self.configFilePath =configFilePath22 self.cf.read(self.configFilePath,encoding="utf-8")23 exceptException as e:24 raisee25

26 defgetItemSection(self,sectionName):27 """

28 获取配置文件中指定section下所有的option键值对,并以字典类型返回给调用者29 注意:30 使用self.cf.items(sectionNmae)此种方法获取到的配置文件中的option内容均被转换成小写31 如loginPage.username被转换成loginpage.username32 :param sectionName:33 :return:34 """

35 optionsDict =dict(self.cf.items(sectionName))36 returnoptionsDict37

38 defgetOptionsBySection(self,sectionName):39 """

40 获取指定sectionName下的所有option41 :param sectionName:42 :return: List Type43 """

44 value =self.cf.options(sectionName)45 returnvalue46

47 defgetOptionValue(self,sectionName,optionName):48 """

49 获取指定section下指定的option值50 :param sectionName:51 :param optionName:52 :return:string 类型53 """

54 value =self.cf.get(sectionName,optionName)55 returnvalue56

57 defgetOptionValueInt(self,sectionName,optionName):58 """

59 获取指定section下指定的option的值60 :param sectionName:61 :param optionName:62 :return:Int 类型63 """

64 value =self.cf.getint(sectionName,optionName)65 returnvalue66

67 defgetSection(self):68 """

69 获取所有的section70 :return: List71 """

72 returnself.cf.sections()73

74 defdump(self):75 """

76 打印配置文件中的所有内容77 :return:78 """

79 sectionsList =self.cf.sections()80 print("="*50)81 for i insectionsList:82 print(i)83 print(self.cf.items(i))84 print("="*50)85

86 defremove_section(self,section):87 """

88 删除section89 :param section:90 :param key:91 :return:92 """

93 self.cf.remove_section(section)94

95

96 defremove_option(self,section,key):97 """

98 删除option99 :param section:100 :param key:101 :return:102 """

103 self.cf.remove_option(section,key)104

105 defadd_section(self,section):106 """

107 添加section108 :param section:109 :return:110 """

111 self.cf.add_section(section)112

113 defset_item(self,section,key,value):114 """

115 给指定的Section设置key,value116 :param section:117 :param key:118 :param value:119 :return:120 """

121 self.cf.set(section,key,value)122

123 defsave(self):124 """

125 保存配置文件126 :return:127 """

128 fp = open(self.configFilePath,'w') #with open(self.configFilePath,"w+") as f:self.cf.write(f)

129 self.cf.write(fp)130 fp.close()131

132

133 if __name__ == "__main__":134 pass

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值