Tips & Traps¶
- Please refer to Parse TOML File in Python for general tips on parsing TOML in Python.
Installatoion¶
In [1]:
pip3 install toml
Parse TOML from a String¶
In [2]:
import toml
In [3]:
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 [4]:
dic = toml.loads(toml_string)
dic
Out[4]:
In [6]:
dic = toml.load(Path("pyproject.toml").open())
dic
Out[6]:
In [7]:
print(toml.dumps(dic))
Parse TOML from a File¶
In [21]:
with open("example.toml", "r") as fin:
dic = toml.load(fin)
dic
Out[21]:
Dump an Object to a TOML String¶
In [ ]:
with open("example.toml", "r") as fin:
dic = toml.load(fin)
In [18]:
print(toml.dumps(dic))
Dump an Object to a TOML File¶
In [ ]:
with open("example.toml", "r") as fin:
dic = toml.load(fin)
In [ ]:
with open("/tmp/example.toml", "w") as fout:
toml.dump(dic, fout)