Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips & Traps¶
- Please refer to Parse TOML File in Python for general tips on parsing TOML in Python.
Installatoion¶
In [1]:
!pip3 install tomlkit
In [2]:
from pathlib import Path
import tomlkit
In [4]:
?tomlkit.loads
In [5]:
?tomlkit.dumps
Parse TOML¶
In [6]:
toml_string = """
# This is a TOML document.
title = "TOML Example"
[owner.info]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00 # First class dates
[database]
server = "192.168.1.1"
ports = [ 8001, 8001, 8002 ]
connection_max = 5000
enabled = true
[servers]
[servers.alpha]
ip = "10.0.0.1"
dc = "eqdc10"
[servers.beta]
ip = "10.0.0.2"
dc = "eqdc10"
[clients]
data = [ ["gamma", "delta"], [1, 2] ]
# Line breaks are OK when inside arrays
hosts = [
"alpha",
"omega"
]
"""
In [7]:
dic = tomlkit.loads(toml_string)
dic
Out[7]:
tomlkit
does not have a method to parse a TOML file directly.
However,
you can read a TOML file as text and then parse it.
In [9]:
dic = tomlkit.loads(Path("pyproject.toml").read_text())
dic
Out[9]:
Dump an Object to a TOML String¶
In [10]:
print(tomlkit.dumps(tomlkit.loads(toml_string)))
tomlkit
does not have a method to dump an object into a TOML file directly.
However,
you can first dump an object into a string
and then write the string into a TOML file.
In [11]:
with Path("/tmp/j.toml").open("w") as fout:
fout.write(tomlkit.dumps(dic))
More¶
In [ ]:
from tomlkit import comment
from tomlkit import document
from tomlkit import nl
from tomlkit import table
doc = document()
doc.add(comment("This is a TOML document."))
doc.add(nl())
doc.add("title", "TOML Example")
# Using doc["title"] = "TOML Example" is also possible
owner = table()
owner.add("name", "Tom Preston-Werner")
owner.add("organization", "GitHub")
owner.add("bio", "GitHub Cofounder & CEO\nLikes tater tots and beer.")
owner.add("dob", datetime(1979, 5, 27, 7, 32, tzinfo=utc))
owner["dob"].comment("First class dates? Why not?")
# Adding the table to the document
doc.add("owner", owner)
database = table()
database["server"] = "192.168.1.1"
database["ports"] = [8001, 8001, 8002]
database["connection_max"] = 5000
database["enabled"] = True
doc["database"] = database
References¶
In [ ]: