在使用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")))
再次執行,結果如下: