LoginSignup
0
1

More than 1 year has passed since last update.

PythonでTomlを読み込もう!

Last updated at Posted at 2022-04-05

TOMLファイルを用意

👇 以下のページから

📖 TOML

👇 コピーして、練習用に テキストファイルを作成

📄example.toml:

# This is a TOML document

title = "TOML Example"

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

[database]
enabled = true
ports = [8000, 8001, 8002]
data = [["delta", "phi"], [3.14]]
temp_targets = { cpu = 79.5, case = 72.0 }

[servers]

[servers.alpha]
ip = "10.0.0.1"
role = "frontend"

[servers.beta]
ip = "10.0.0.2"
role = "backend"

pytomlpp をインストール

👇 環境に pytomlpp をインストール

pip install pytomlpp

main.py ファイル作成

👇 コピー貼り付け

📄main.py:

import pytomlpp

with open('example.toml', mode='r', encoding='utf-8') as f:
    text = f.read()

# print(text)

# ここに Toml の処理を書く
print("Tomlの読込")
doc = pytomlpp.loads(text)

print(f"ip は {doc['servers']['alpha']['ip']}")

実行

python.exe main.py

出力結果

Tomlの読込
ip は 10.0.0.1
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1