configparser (Python 3) / ConfigParser (Python 2)INI 格式:[section] 區塊 + key = value 鍵值對,支援註解 #/;、多行值縮排。
import configparser
cfg = configparser.ConfigParser()
cfg.read('settings.ini', encoding='utf-8') # Python 3 需指定 encoding
# 讀取
host = cfg.get('database', 'host')
port = cfg.getint('database', 'port')
debug = cfg.getboolean('app', 'debug')
# 寫入/修改
if not cfg.has_section('database'):
cfg.add_section('database')
cfg.set('database', 'host', '127.0.0.1')
cfg.set('database', 'port', '5432')
with open('settings.ini', 'w', encoding='utf-8') as f:
cfg.write(f)
import configparser
import os
from pathlib import Path
from typing import Any, Optional
class IniConfig:
_instance = None
_default_path = Path(__file__).with_name('config.ini')
def __new__(cls, path: Optional[str] = None):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._cfg = configparser.ConfigParser()
cls._instance._path = Path(path) if path else cls._default_path
cls._instance._load()
return cls._instance
def _load(self):
if self._path.exists():
self._cfg.read(self._path, encoding='utf-8')
else:
# 建立預設設定
self._cfg['app'] = {'debug': 'false', 'log_level': 'INFO'}
self._cfg['database'] = {'host': 'localhost', 'port': '5432'}
self.save()
def save(self):
with open(self._path, 'w', encoding='utf-8') as f:
self._cfg.write(f)
# 型別安全取值
def get(self, section: str, key: str, fallback: Any = None) -> str:
return self._cfg.get(section, key, fallback=fallback)
def getint(self, section: str, key: str, fallback: int = 0) -> int:
return self._cfg.getint(section, key, fallback=fallback)
def getfloat(self, section: str, key: str, fallback: float = 0.0) -> float:
return self._cfg.getfloat(section, key, fallback=fallback)
def getboolean(self, section: str, key: str, fallback: bool = False) -> bool:
return self._cfg.getboolean(section, key, fallback=fallback)
# 寫入自動轉字串
def set(self, section: str, key: str, value: Any):
if not self._cfg.has_section(section):
self._cfg.add_section(section)
self._cfg.set(section, key, str(value))
self.save()
# 區塊操作
def add_section(self, section: str):
if not self._cfg.has_section(section):
self._cfg.add_section(section)
self.save()
def sections(self):
return self._cfg.sections()
def options(self, section: str):
return self._cfg.options(section)
def as_dict(self) -> dict:
return {s: dict(self._cfg.items(s)) for s in self._cfg.sections()}
cfg = IniConfig() # 單例
# 讀取
db_host = cfg.get('database', 'host')
db_port = cfg.getint('database', 'port')
debug = cfg.getboolean('app', 'debug')
# 寫入
cfg.set('database', 'host', '192.168.1.100')
cfg.set('app', 'log_level', 'DEBUG')
# 新增區塊
cfg.add_section('redis')
cfg.set('redis', 'url', 'redis://localhost:6379/0')
# 導出完整字典
print(cfg.as_dict())
# config.ini
[paths]
base_dir = /var/www
static_dir = %(base_dir)s/static
media_dir = ${base_dir}/media # ExtendedInterpolation 語法
# 程式碼
cfg = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
cfg.read('config.ini')
print(cfg.get('paths', 'static_dir')) # /var/www/static
# 預設不區分大小寫 (optionxform = str.lower)
# 保持大小寫:
cfg = configparser.ConfigParser()
cfg.optionxform = str # 關鍵:保持原大小寫
# 依序讀取,後者覆蓋前者
cfg.read(['/etc/app/defaults.ini', '/etc/app/prod.ini', 'local.ini'])
REQUIRED = {
'database': ['host', 'port', 'user', 'password'],
'app': ['secret_key']
}
def validate(cfg: configparser.ConfigParser):
for section, keys in REQUIRED.items():
if not cfg.has_section(section):
raise ValueError(f"缺少區塊: [{section}]")
for k in keys:
if not cfg.has_option(section, k):
raise ValueError(f"[{section}] 缺少鍵: {k}")
ConfigParser vs configparser),read() 不支援 encoding 參數 (Py2 需自行解碼)。getboolean 接受 1/0, true/false, yes/no, on/off (不區分大小寫)。fallback 僅在鍵不存在時生效,空字串 "" 會被視為有值。fcntl/msvcrt) 或改用 SQLite/Redis。