https://blog.csdn.net/u011541946/article/details/70174276
遇到的问题:NobrowserTape 原因为新建文件夹错误,新建文件夹为 new-directory
本文来介绍下Python中如何读取配置文件。任何一个项目,都涉及到了配置文件和管理和读写,Python支持很多配置文件的读写,这里我们就介绍一种配置文件格式的读取数据,叫ini文件。Python中有一个类ConfigParser支持读ini文件。
1. 在项目下,新建一个文件夹(右键new-directory),叫config,然后在这个文件夹下新建一个file类型(new-file)的文件:config.ini
文件内容如下:
- # this is config file, only store browser type and server URL
- [browserType]
- #browserName = Firefox
- browserName = Chrome
- #browserName = IE
- [testServer]
- URL = https://www.baidu.com
- #URL = http://www.google.com
这里采用:
os.path.dirname(os.path.abspath('.'))
3. 在另外一个包下新建一个测试类,用来测试读取配置文件是否正常。
- # coding=utf-8
- import ConfigParser
- import os
- class TestReadConfigFile(object):
- def get_value(self):
- root_dir = os.path.dirname(os.path.abspath('.')) # 获取项目根目录的相对路径
- print root_dir
- config = ConfigParser.ConfigParser()
- file_path = os.path.dirname(os.path.abspath('.')) + '/config/config.ini'
- config.read(file_path)
- browser = config.get("browserType", "browserName")
- url = config.get("testServer", "URL")
- return(browser,url) # 返回的是一个元组
- trcf = TestReadConfigFile()
- print trcf.get_value()