前言
大家應該接觸過.ini格式的配置文件。配置文件就是把一些配置相關信息提取出去來進行單獨管理,如果以后有變動只需改配置文件,無需修改代碼。
特別是后續做自動化的測試,代碼和數據分享,進行管理。比如說發送郵件的郵箱配置信息、數據庫連接等信息。
今天介紹一些如何用Python讀取ini配置文件。
一、ini文件格式
- 格式如下:
;這是注釋
[section] key1 = value1 key2= value2 [section
]
key3= value3
key4= value4
[section]
:ini的section模塊,是下面參數值的一個統稱,方便好記就行key = value
:參數以及參數值- ini 文件中,使用英文分號“;”進行注釋
- section不能重復,里面數據通過section去查找,每個seletion下可以有多個key和vlaue的鍵值
Py3和Py2區別
二、讀取ini文件
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'))
運行結果:
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')]
三、修改並寫入ini文件
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+'))
如果對軟件測試、接口測試、自動化測試、技術同行、持續集成、面試經驗交流。感興趣可以進到893694563,群內會有不定期的分享測試資料。
如果文章對你有幫助,麻煩伸出發財小手點個贊,感謝您的支持,你的點贊是我持續更新的動力。