Python+Selenium中级篇之-Python读取配置文件内容

本文来介绍下Python中如何读取配置文件。任何一个项目,都涉及到了配置文件和管理和读写,Python支持很多配置文件的读写,这里我们就介绍一种配置文件格式的读取数据,叫ini文件。Python中有一个类ConfigParser支持读ini文件。

1. 在项目下,新建一个文件夹,叫config,然后在这个文件夹下新建一个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
2. 百度搜索一下,python中如何获取当前项目的根目录的相对路径
这里采用:

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()
      你可以试试更改config.ini的内容,看看测试打印出来是不是你更改的东西,在配置文件一般#表示注释,你想要哪行配置代码起作用,你就把前面的#去除,并且在注释其他同一个区域。在ini文件中 中括号包裹起来的部分叫section,了解一下就可以。

原文地址:https://www.cnblogs.com/wangyinghao/p/10607444.html