【Python】Python ~ TOML ~

■ はじめに

TOMLファイルを読み込み
そのデータ内を使うツールが必要になりそうなので
PythonでTOMLをどう扱うかを調べてみた

なお、TOMLについては、以下の関連記事を参照のこと

TOML
https://dk521123.hatenablog.com/entry/2023/04/25/103533

目次

【1】Python で TOML を扱うには
 1)Python3.11以降
 2)Python 3.11未満
【2】使用上の注意
 1)tomllibは書き込み非対応
【3】サンプル
 例1:tomlkit (Python3.10)

【1】Python で TOML を扱うには

Python のバージョンによって異なる

1)Python3.11以降

* 標準ライブラリ「tomllib」が完備

https://docs.python.org/ja/dev/library/tomllib.html

2)Python 3.11未満

* pip などでライブラリをインストールする必要がある
 => 色々あるっぽい、、、toml, tomlkit and so on

【2】使用上の注意

1)tomllibは書き込み非対応

* あくまで読み込みのみ

【3】サンプル

読み込み用TOML:input.toml

# This is a comment
title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00 # date type

[[table_array]]
key1 = "value1"

例1:tomlkit (Python3.10)

from tomlkit.toml_file import TOMLFile

toml = TOMLFile("./input.toml")
toml_data = toml.read()
print(f"toml_data: type = {type(toml_data)}, value = {toml_data}\n")

title = toml_data.get("title")
print(f"title = {title}")
owner = toml_data.get("owner")
print(f"owner = {owner}")

tomlkit

pip install tomlkit

Output

toml_data: type = <class 'tomlkit.toml_document.TOMLDocument'>, value = {'title': 'TOML Example', 'owner': {'name': 'Tom Preston-Werner', 'dob': DateTime(1979, 5, 27, 7, 32, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=57600), '-08:00'))}, 'table_array': [{'key1': 'value1'}]}

title = TOML Example
owner = {'name': 'Tom Preston-Werner', 'dob': DateTime(1979, 5, 27, 7, 32, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=57600), '-08:00'))}

参考文献

tomllib
https://atmarkit.itmedia.co.jp/ait/articles/2312/12/news018.html
https://gihyo.jp/article/2022/11/monthly-python-2211
toml
https://qiita.com/tetrapod117/items/d27388d5ed9386c1efd6
https://www.naka-sys.okinawa/python-toml/
tomlkit
https://7rikazhexde-techlog.hatenablog.com/entry/2023/03/10/234923

関連記事

Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 可変長引数 / args kwargs ~
https://dk521123.hatenablog.com/entry/2023/11/01/000915
外部コマンド実行 ~
https://dk521123.hatenablog.com/entry/2021/08/04/224716
TOML
https://dk521123.hatenablog.com/entry/2023/04/25/103533