【Python 3.6.1】读配置文件
一、配置文件格式
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[root@dt xxf]# pwd /root/xxf [root@dt xxf]# cat db.conf [odb_100] ip = 192.168.1.100 port = 1521 service_name = ORCL [odb_108] ip = 192.168.1.108 port = 1526 service_name = ORA11GR2 [root@dt xxf]# |
二、configparser模块
python2和python3在读配置文件时引用的模块是不同的,或者说名字上做了些许的改变,python2引用的模块ConfigParser,python3引用的模块configparser,本测试环境是python3,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
[root@dt xxf]# cat rconf.py # 引用configparser模块 import configparser # 初始化实例,得到一个对象cf cf = configparser.ConfigParser() # 读取相对路径下的db.conf文件 cf.read("db.conf") # 读配置文件中所有的section,以数组的形式显示 s = cf.sections() print ("section:",s) # 打印88个“-”作为分隔符 print ("-" * 88) # 读取option,可以简单的理解为Key+Value中的Key,以数组的形式显示 o1 = cf.options("odb_100") print ("options:odb_100",o1) o2 = cf.options("odb_108") print ("options:odb_108",o2) print ("-" * 88) # 读取指定标签的Key及Value,以数据形式显示 itm = cf.items("odb_100") print ("items:odb100",itm) print ("-" * 88) # 读取指定标签的Value v_ip = cf.get("odb_108","ip") v_port = cf.get("odb_108","port") v_sname = cf.get("odb_108","service_name") print ("ip:",v_ip) print ("port:",v_port) print ("service_name:",v_sname) [root@dt xxf]# |
三、运行结果:
1 2 3 4 5 6 7 8 9 10 11 12 |
[root@dt xxf]# python3 rconf.py section: ['odb_100', 'odb_108'] ---------------------------------------------------------------------------------------- options:odb_100 ['ip', 'port', 'service_name'] options:odb_108 ['ip', 'port', 'service_name'] ---------------------------------------------------------------------------------------- items:odb100 [('ip', '192.168.1.100'), ('port', '1521'), ('service_name', 'ORCL')] ---------------------------------------------------------------------------------------- ip: 192.168.1.108 port: 1526 service_name: ORA11GR2 [root@dt xxf]# |