tomllib --- 剖析 TOML 檔案¶
在 3.11 版被加入.
原始碼:Lib/tomllib
此模組提供了剖析 TOML 1.0.0 (Tom's Obvious Minimal Language, https://toml.io) 的一個介面,此模組並不支援寫入 TOML。
也參考
Tomli-W 套件是一個 TOML 編寫器,可以與此模組結合使用,以提供標準函式庫中 marshal 和 pickle 模組之使用者所熟悉的寫入 API。
也參考
TOML 工具套件是一個保留風格且具有讀寫能力的 TOML 函式庫。若要編輯已存在的 TOML 文件,建議用它來替換此模組。
此模組定義了以下函式:
- tomllib.load(fp, /, *, parse_float=float)¶
 讀取一個 TOML 檔案。第一個引數應為一個可讀取的二進位檔案物件。回傳一個
dict。用這個轉換表將 TOML 型別轉換成 Python 的。parse_float 會被呼叫於要解碼的每個 TOML 浮點數字串。預設情況下,這相當於
float(num_str)。若有使用另一種資料型別或剖析器的 TOML 浮點數(例如decimal.Decimal),這就派得上用場。可呼叫物件不得回傳dict或list,否則會引發ValueError。不合格的 TOML 文件會使得
TOMLDecodeError被引發。
- tomllib.loads(s, /, *, parse_float=float)¶
 自一個
str物件載入成 TOML。回傳一個dict。用這個轉換表轉換 TOML 型別成 Python 的。parse_float 引數和load()中的相同。不合格的 TOML 文件會使得
TOMLDecodeError被引發。
以下為可用的例外:
- exception tomllib.TOMLDecodeError(msg, doc, pos)¶
 Subclass of
ValueErrorwith the following additional attributes:- msg¶
 The unformatted error message.
- doc¶
 The TOML document being parsed.
- pos¶
 The index of doc where parsing failed.
- lineno¶
 The line corresponding to pos.
- colno¶
 The column corresponding to pos.
在 3.14 版的變更: Added the msg, doc and pos parameters. Added the
msg,doc,pos,linenoandcolnoattributes.在 3.14 版之後被棄用: Passing free-form positional arguments is deprecated.
範例¶
剖析一個 TOML 檔案:
import tomllib
with open("pyproject.toml", "rb") as f:
    data = tomllib.load(f)
剖析一個 TOML 字串:
import tomllib
toml_str = """
python-version = "3.11.0"
python-implementation = "CPython"
"""
data = tomllib.loads(toml_str)
轉換表¶
TOML  | 
Python  | 
|---|---|
TOML 文件  | 
dict  | 
string  | 
str  | 
integer  | 
int  | 
float  | 
float(可透過 parse_float 調整)  | 
boolean  | 
bool  | 
偏移日期時間 (offset date-time)  | 
datetime.datetime(設定   | 
本地日期時間 (local date-time)  | 
datetime.datetime(設定   | 
本地日期 (local date)  | 
datetime.date  | 
本地時間 (local time)  | 
datetime.time  | 
array  | 
list  | 
table  | 
dict  | 
行內表格 (inline table)  | 
dict  | 
表格陣列 (array of tables)  | 
dict 串列 (list of dicts)  |