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 import ConfigParser
11
12
13 class ParseConfigFile():
14
15 def __init__(self,configFilePath=None):
16 self.cf = ConfigParser()
17 try:
18 if configFilePath is None:
19 raise FileNotFoundError("Can't found config file!")
20 else:
21 self.configFilePath = configFilePath
22 self.cf.read(self.configFilePath,encoding="utf-8")
23 except Exception as e:
24 raise e
25
26 def getItemSection(self,sectionName):
27 """
28 获取配置文件中指定section下所有的option键值对,并以字典类型返回给调用者
29 注意:
30 使用self.cf.items(sectionNmae)此种方法获取到的配置文件中的option内容均被转换成小写
31 如loginPage.username被转换成loginpage.username
32 :param sectionName:
33 :return:
34 """
35 optionsDict = dict(self.cf.items(sectionName))
36 return optionsDict
37
38 def getOptionsBySection(self,sectionName):
39 """
40 获取指定sectionName下的所有option
41 :param sectionName:
42 :return: List Type
43 """
44 value = self.cf.options(sectionName)
45 return value
46
47 def getOptionValue(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 return value
56
57 def getOptionValueInt(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 return value
66
67 def getSection(self):
68 """
69 获取所有的section
70 :return: List
71 """
72 return self.cf.sections()
73
74 def dump(self):
75 """
76 打印配置文件中的所有内容
77 :return:
78 """
79 sectionsList = self.cf.sections()
80 print("="*50)
81 for i in sectionsList:
82 print(i)
83 print(self.cf.items(i))
84 print("="*50)
85
86 def remove_section(self,section):
87 """
88 删除section
89 :param section:
90 :param key:
91 :return:
92 """
93 self.cf.remove_section(section)
94
95
96 def remove_option(self,section,key):
97 """
98 删除option
99 :param section:
100 :param key:
101 :return:
102 """
103 self.cf.remove_option(section,key)
104
105 def add_section(self,section):
106 """
107 添加section
108 :param section:
109 :return:
110 """
111 self.cf.add_section(section)
112
113 def set_item(self,section,key,value):
114 """
115 给指定的Section设置key,value
116 :param section:
117 :param key:
118 :param value:
119 :return:
120 """
121 self.cf.set(section,key,value)
122
123 def save(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