ConfigParser 是 Python 標準庫處理 INI 格式配置檔的核心模組,支援區塊、鍵值對、型別轉換、變數插值與寫入更新。本文詳細說明讀寫 API、三種解析器差異與實戰範例。
核心讀取 API
| 方法 | 說明 |
read(filename) | 讀取單一或多個配置檔 |
sections() | 回傳所有區塊名稱列表 |
options(section) | 回傳指定區塊所有鍵名 |
items(section) | 回傳指定區塊所有鍵值對 |
get(section, option) | 取得字串值 |
getint/getfloat/getboolean | 取得對應型別值 |
核心寫入 API
| 方法 | 說明 |
add_section(section) | 新增區塊 |
set(section, option, value) | 設定鍵值(需配合 write 持久化) |
write(fileobj) | 寫入檔案物件 |
基本範例
配置檔 test.conf
[sec_a]
a_key1 = 20
a_key2 = 10
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = $r
b_key4 = 127.0.0.1
讀取與型別轉換
import ConfigParser
cf = ConfigParser.ConfigParser()
cf.read("test.conf")
secs = cf.sections() # ['sec_b', 'sec_a']
opts = cf.options("sec_a") # ['a_key1', 'a_key2']
kvs = cf.items("sec_a") # [('a_key1', "i'm value"), ('a_key2', '22')]
str_val = cf.get("sec_a", "a_key1") # 字串
int_val = cf.getint("sec_a", "a_key2") # 整數 22
更新與寫入
cf.set("sec_b", "b_key3", "new-$r")
cf.set("sec_b", "b_newkey", "new-value")
cf.add_section('a_new_section')
cf.set('a_new_section', 'new_key', 'new_value')
cf.write(open("test.conf", "w"))
三大解析器差異:變數插值支援
配置檔 test2.conf
[portal]
url = https://%(host)s:%(port)s/Portal
host = localhost
port = 8080
RawConfigParser:不解析插值
cf = ConfigParser.RawConfigParser()
cf.read("test2.conf")
cf.get("portal", "url") # "https://%(host)s:%(port)s/Portal"
cf.set("portal", "url2", "%(host)s:%(port)s")
cf.get("portal", "url2") # "%(host)s:%(port)s"
ConfigParser / SafeConfigParser:支援插值
cf = ConfigParser.ConfigParser() # 或 SafeConfigParser
cf.read("test2.conf")
cf.get("portal", "url") # "https://localhost:8080/Portal"
cf.set("portal", "url2", "%(host)s:%(port)s")
cf.get("portal", "url2") # "localhost:8080"
選擇指南
| 解析器 | 插值支援 | 安全性 | 推薦場景 |
| RawConfigParser | 否 | 最高(無注入風險) | 純資料儲存、不信任輸入 |
| ConfigParser | 是 | 中(可能遞迴插值) | 一般應用、需變數引用 |
| SafeConfigParser | 是 | 較高(驗證插值語法) | 推薦預設選擇 |
Python 3 遷移提示
- 模組重命名為
configparser(小寫)
SafeConfigParser 併入 ConfigParser
readfp() 棄用,改用 read_file()