Python 3.11+tomllibfunction
tomllib.load()
reading TOML
Reads TOML from a file opened in binary mode and returns a dict, for example pyproject.toml.
Syntax
with open(path, 'rb') as f: data = tomllib.load(f, *, parse_float=float)
The file must be opened as 'rb': text mode raises TypeError, but in return the encoding is always UTF-8 and cannot be wrong. The module only reads; it cannot write TOML, which needs a third-party library such as tomli-w. TOML dates become datetime objects, not strings.
Examples
import tomllib
with open('config.toml', 'w', encoding='utf-8') as f:
f.write('[server]\nport = 8080\nhosts = ["a", "b"]\n')
with open('config.toml', 'rb') as f:
data = tomllib.load(f)
print(data) # → {'server': {'port': 8080, 'hosts': ['a', 'b']}}
import tomllib
open('c.toml', 'w').close()
try:
with open('c.toml', encoding='utf-8') as f:
tomllib.load(f)
except TypeError as e:
print(type(e).__name__) # → TypeError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy