Python 读取写入配置文件很方便, 可使用内置的 configparser 模块
配置文件: config.INI
- [oppo]
- platformName = Android
- platformVersion = 6.0
- deviceName = weiruoyu
- appPackage = com.sina.weibo
- appActivity = .SplashActivity
- url = http://127.0.0.1:4723/wd/hub
- [MySQL]
- host=127.0.0.1
- port=3306
- user=root
- password=123456
- [logging]
- level = 20
- path = /usr/test
- server = 192.168.1.8
源码:
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- import ConfigParser
- # ######## 函数 ############
- conf = ConfigParser.ConfigParser()
- a = conf.read("config.ini")
- print "config.inf =", a
- print conf.items("oppo")
- secs = conf.sections()
- print "secs=", secs
- options = conf.options("mysql")
- print "options=", options
- items = conf.items("mysql")
- print "items=", items
- host = conf.get("mysql","host")
- print "host=",host
输出:
- config.inf = ['config.ini']
- [('platformname', 'Android'), ('platformversion', '6.0'), ('devicename', 'weiruoyu'), ('apppackage', 'com.sina.weibo'), ('appactivity', '.SplashActivity'), ('url', 'http://127.0.0.1:4723/wd/hub')]
- secs= ['oppo', 'mysql', 'logging']
- options= ['host', 'port', 'user', 'password']
- items= [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')]
- host= 127.0.0.1
- [Finished in 0.1s]
参考如下:
- cf.read("E:\Crawler\config.ini") # 读取配置文件, 如果写文件的绝对路径, 就可以不用 os 模块
- secs = cf.sections() # 获取文件中所有的 section(一个配置文件中可以有多个配置, 如数据库相关的配置, 邮箱相关的配置,
每个 section 由 [] 包裹, 即[section]), 并以列表的形式返回
- print(secs)
- options = cf.options("Mysql-Database") # 获取某个 section 名为 MySQL-Database 所对应的键
- print(options)
- items = cf.items("Mysql-Database") # 获取 section 名为 MySQL-Database 所对应的全部键值对
- print(items)
- host = cf.get("Mysql-Database", "host") # 获取 [MySQL-Database] 中 host 对应的值
- print(host)
参考网址如下:
python 读取配置文件 && 简单封装 https://www.cnblogs.com/hanmk/p/9843136.html
python configparser 模块 https://www.cnblogs.com/lhly/p/8066898.html
来源: http://www.bubuko.com/infodetail-2945121.html