你们应该接触过.ini格式的配置文件。配置文件就是把一些配置相关信息提取出去来进行单独管理,若是之后有变更只需改配置文件,无需修改代码。特别是后续作自动化的测试,须要拎出一部分配置信息,进行管理。好比说发送邮件的邮箱配置信息、数据库链接等信息。python
今天介绍一些如何用Python读取ini配置文件。数据库
; comments [section1] Param1 = value1 Param2= value2 [section2] Param3= value3 Param4= value4
[section]
:ini的section模块,是下面参数值的一个统称,方便好记就行。Param = value
:参数以及参数值。Python自带有读取配置文件的模块ConfigParser,配置文件不区分大小写。
有一系列的方法可提供。函数
read(filename)
:读取文件内容sections()
:获得全部的section,并以列表的形式返回。options(section)
:获得该section的全部option。items(section)
:获得该section的全部键值对。get(section,option)
:获得section中option的值,返回string类型。getint(section,option)
:获得section中option的值,返回int类型。举个栗子:测试
import os import configparser # 当前文件路径 proDir = os.path.split(os.path.realpath(__file__))[0] # 在当前文件路径下查找.ini文件 configPath = os.path.join(proDir, "config.ini") print(configPath) conf = configparser.ConfigParser() # 读取.ini文件 conf.read(configPath) # get()函数读取section里的参数值 name = conf.get("section1","name") print(name) print(conf.sections()) print(conf.options('section1')) print(conf.items('section1'))
运行结果:code
D:\Python_project\python_learning\config.ini 2号 ['section1', 'section2', 'section3', 'section_test_1'] ['name', 'sex', 'option_plus'] [('name', '2号'), ('sex', 'female'), ('option_plus', 'value')]
write(fp)
:将config对象写入至某个ini格式的文件中。add_section(section)
:添加一个新的section。set(section,option,value)
:对section中的option进行设置,须要调用write将内容写入配置文件。remove_section(section)
:删除某个section。remove_option(section,option)
:删除某个section下的option举个栗子:接上部分对象
# 写入配置文件 set() # 修改指定的section的参数值 conf.set("section1",'name','3号') # 增长指定section的option conf.set("section1","option_plus","value") name = conf.get("section1","name") print(name) conf.write(open(configPath,'w+')) # 增长section conf.add_section("section_test_1") conf.set("section_test_1","name","test_1") conf.write(open(configPath,'w+'))
来句鸡汤:相信将来会越走越好 那么就确定要坚持 我但愿将来的我不会让本身后悔rem
❤ thanks for watching, keep on updating...get