Python3 中 configparser 使用注意事项

在使用configparser时候应注意:

①配置文件(ini文件)的存放位置:配置文件和调用文件放在同一个文件包下面。

使用read()函数读取并解析配置文件时,直接写配置文件(ini文件)的文件名即可。

例如:

cf=ConfigParser()                   #实例化
cf.read("PageElementLocator.ini") #读取并解析配置文

②配置文件(ini文件)的存放位置:配置文件和调用文件未放在同一个文件包下面。

使用read()函数读取并解析配置文件时,则需要写配置文件(ini文件)存放绝对路径。

例如: 

parentDirPath=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   #os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 获取当前文件所在目录的绝对路径 注意:该路径不包含当前目录
path=parentDirPath+'\\config\\PageElementLocator.ini'      #获取配置文件的的绝对路径

cf=ConfigParser()                   #实例化
cf.read(path) #读取并解析配置文件

未遵循上述两点,或者配置文件的路径写错,均会出现错误configparser.NoSectionError: No section

③items()此种方法获取到的配置文件中的options内容均被转换成小写。

例如:test.ini 内容:

[peizhi]
A=Hello
B=Word

         test.py 内容:

from configparser import ConfigParser

cf=ConfigParser()
cf.read("test.ini")
print(cf.items("peizhi"))

  执行结果:items获取配置文件中指定的section下的所有键值对。

如果需要把items的返回结果以字典类型返回,那么需使用dict()方法。修改 test.py 内容:

from configparser import ConfigParser

cf=ConfigParser()
cf.read("test.ini")
print(dict(cf.items("peizhi")))

再次执行,结果如下: 

 

 

 

          

 

posted @ 2018-10-09 10:56  奔跑中的兔子  阅读(10141)  评论(0编辑  收藏  举报