ConfigParser 模組完整教學:INI 讀寫、變數插值、三大解析器差異ConfigParser 是 Python 標準庫處理 INI 格式配置檔的利器。本文涵蓋讀寫 API、變數插值機制、RawConfigParser/ConfigParser/SafeConfigParser 三類差異,並提供完整可運行範例。
import ConfigParser
cf = ConfigParser.ConfigParser()
cf.read("test.conf")
cf.sections() # 所有 section 列表
cf.options("sec_a") # section 所有 key
cf.items("sec_a") # section 所有 key-value
cf.get("sec_a", "a_key1") # 字串
cf.getint("sec_a", "a_key2") # 整數
cf.getfloat(...), cf.getboolean(...)
cf.set("sec_b", "b_key3", "new-value") # 修改/新增 key
cf.add_section("a_new_section") # 新增 section
cf.set("a_new_section", "new_key", "new_value")
cf.write(open("test.conf", "w")) # 寫回檔案
test.conf
[sec_a]
a_key1 = i'm value
a_key2 = 22
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = $r
b_key4 = 127.0.0.1
sections: ['sec_b', 'sec_a']
options: ['a_key1', 'a_key2']
sec_a: [('a_key1', "i'm value"), ('a_key2', '22')]
value for sec_a's a_key1: i'm value
value for sec_a's a_key2: 22
更新後檔案自動重排 section 順序。
%(var)s
# test2.conf
[portal]
url = https://%(host)s:%(port)s/Portal
host = localhost
port = 8080
| 解析器 | 讀取 url | 寫入 url2 = %(host)s:%(port)s 後讀取 |
|---|---|---|
RawConfigParser | https://%(host)s:%(port)s/Portal(原樣) | %(host)s:%(port)s(原樣) |
ConfigParser | https://localhost:8080/Portal(插值) | localhost:8080(插值) |
SafeConfigParser | https://localhost:8080/Portal | localhost:8080 |
結論:
ConfigParser 或 SafeConfigParser(Py3 僅保留 ConfigParser,已安全)。% 符號(如 SQL 片段) → 用 RawConfigParser。import configparserSafeConfigParser 移除,ConfigParser 已安全化。readfp 棄用,改用 read_file。ConfigParser(allow_no_value=True)。cf.read(['base.conf', 'override.conf']) 後讀覆蓋先讀。cf.set(sec, k, os.getenv(k, v))。getlist、getdict 解析 JSON/逗號分隔值。ConfigParser 以簡單 INI 格式支援分層配置、變數插值、型別轉換,是中小型專案零依賴配置管理的首選。