TOMLしたい(tomllib

1import tomllib
2from pathlib import Path
3
4fname = Path("設定ファイル.toml")
5with fname.open("rb") as f:
6    config = tomllib.load(f)

tomllibはPython3.11で標準モジュールに追加された読み込み専用のTOMLパーサーです。 TOML形式のファイルを読み込み、辞書型に変換します。

注釈

tomllibは読み込み専用のため、TOMLファイルを書き出す機能はありません。 書き出したい場合は、tomli-wのような サードパーティ製パッケージを使う必要があります。

キー/バリューしたい

1integer = 1
2string = "two"
3number = 3.0
1{
2    "integer": 1,
3    "string": "two",
4    "number": 3.0,
5}

リストしたい

1integers = [1, 2, 3]
2strings = ["one", "two", "three"]
3mixed = [1, "two", 3.0]
1{
2    "integers": [1, 2, 3],
3    "strings": ["one", "two", "three"],
4    "mixed": [1, "two", 3.0],
5}

テーブルしたい([table]

1[owner]
2name = "Tom"
3age = 36
1{
2    "owner": {
3        "name": "Tom",
4        "age": 36,
5    }
6}

[table]のようにセクション名を書くと、キー/バリューをまとめたテーブル(辞書)になります。

インライン・テーブルしたい({ key = value }

1point = { x = 1, y = 2 }
1{
2    "point": {"x": 1, "y": 2}
3}

{ key = value, ... }のように1行で書くテーブルを、インライン・テーブルと呼びます。 [table]と違い、複数行に分けて書くことはできません。

配列テーブルしたい([[table]]

1[[record]]
2run_id = 1
3distance = 10.0
4
5[[record]]
6run_id = 2
7distance = 20.0
1{"record":
2    [
3        {"run_id": 1, "distance": 10.0},
4        {"run_id": 2, "distance": 20.0},
5    ]
6}

リファレンス