一、configparser模塊是什么
可以用來操作后綴為 .ini 的配置文件;
python標準庫(就是python自帶的意思,無需安裝)
二、configparser模塊基本使用
2.1 讀取 ini 配置文件
1
2
3
4
5
6
7
8
9
|
#存在 config.ini 配置文件,內容如下: [DEFAULT] excel_path = .. /test_cases/case_data .xlsx log_path = .. /logs/test .log log_level = 1 [email] user_name = 32@qq.com password = 123456 |
使用configparser模塊讀取配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import configparser #創建配置文件對象 conf = configparser.ConfigParser() #讀取配置文件 conf.read( 'config.ini' , encoding = "utf-8" ) #列表方式返回配置文件所有的section print ( conf.sections() ) #結果:['default', 'email'] #列表方式返回配置文件email 這個section下的所有鍵名稱 print ( conf.options( 'email' ) ) #結果:['user_name', 'password'] #以[(),()]格式返回 email 這個section下的所有鍵值對 print ( conf.items( 'email' ) ) #結果:[('user_name', '32@qq.com'), ('password', '123456')] #使用get方法獲取配置文件具體的值,get方法:參數1-->section(節) 參數2-->key(鍵名) value = conf.get( 'default' , 'excel_path' ) print (value) |
2.2 寫入 ini 配置文件(字典形式)
1
2
3
4
5
6
7
8
9
10
|
import configparser #創建配置文件對象 conf = configparser.ConfigParser() #'DEFAULT'為section的名稱,值中的字典為section下的鍵值對 conf[ "DEFAULT" ] = { 'excel_path' : '../test_cases/case_data.xlsx' , 'log_path' : '../logs/test.log' } conf[ "email" ] = { 'user_name' : '32@qq.com' , 'password' : '123456' } #把設置的conf對象內容寫入config.ini文件 with open ( 'config.ini' , 'w' ) as configfile: conf.write(configfile) |
2.3 寫入 ini 配置文件(方法形式)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import configparser #創建配置文件對象 conf = configparser.ConfigParser() #讀取配置文件 conf.read( 'config.ini' , encoding = "utf-8" ) #在conf對象中新增section conf.add_section( 'webserver' ) #在section對象中新增鍵值對 conf. set ( 'webserver' , 'ip' , '127.0.0.1' ) conf. set ( 'webserver' , 'port' , '80' ) #修改'DEFAULT'中鍵為'log_path'的值,如沒有該鍵,則新建 conf. set ( 'DEFAULT' , 'log_path' , 'test.log' ) #刪除指定section conf.remove_section( 'email' ) #刪除指定鍵值對 conf.remove_option( 'DEFAULT' , 'excel_path' ) #寫入config.ini文件 with open ( 'config.ini' , 'w' ) as f: conf.write(f) |
上述3個例子基本闡述了configparser模塊的核心功能項;
- 例1中,encoding="utf-8"為了放置讀取的適合中文亂碼;
- 例2你可以理解為在字典中新增數據,鍵:配置文件的section,字符串格式;值:section的鍵值對,字典格式;
- 例3中在使用add_section方法時,如果配置文件存在section,則會報錯;而set方法在使用時,有則修改,無則新建。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/dream66/p/12605038.html