python - 配置文件

 1 #配置文件
 2 #.ini .properties .conf 等都是配置文件
 3 #section 片段[]; option 选项
 4 #同一个section下option都是唯一的
 5 
 6 #语法
 7 #[secion]
 8 #option = values
 9 #....
10 
11 #例如
12 # [student1]
13 # name=小丫
14 # age=23
15 
16 #配置文件里面的数据,读取出来后,类型都是字符串
17 #如何读取配置文件?
18 import configparser
19 
20 # cf = configparser.ConfigParser()#创建一个可以读取配置文件的对象
21 #
22 # cf.read('case.conf',encoding ='gbk')#打开配置文件;当配置文件含中文时,必须加上encoding='utf-8'or encoding ='gbk'
23 #
24 # print(cf.sections())#读取配置文件里面全部的sections
25 # print(cf.options('student1'))#读指定sections里面的全部的options
26 #
27 # print(cf.get('student1','name'))#读指定sections里面的指定的options
28 # print(cf['student1']['name'])#读指定sections里面的指定的options
29 #
30 # print(type(cf.get('student1','age')))#配置文件里面的数据,读取出来后,类型都是字符串
31 
32 #写一个类
33 class ReadConfig():
34     def read_config(self,file_name,section,option):
35         cf = configparser.ConfigParser()#创建对象
36         cf.read(file_name,encoding ='gbk')#打开配置文件
37         value=cf.get(section,option)
38         return value
39 if __name__ == '__main__':
40     value=ReadConfig().read_config('case.conf','student1','name')
41     print(value)

执行结果:

猜你喜欢

转载自www.cnblogs.com/Aphrodite/p/10092939.html
今日推荐