Skip to content
shellhacks.dev
Python

Read a TOML File in Python with tomllib

Read a TOML file with tomllib.load in Python 3.11 or later. Open the file in binary mode, or it raises TypeError, and use tomllib.loads for a string.

1 min read
Summarize in AI

A tool keeps its settings in pyproject.toml style files, and the standard library can now parse them without a package.

Python
import tomllib

with open("app.toml", "w") as f:
    f.write('name = "web"\nports = [8080, 8081]\n[db]\nhost = "localhost"\n')

with open("app.toml", "rb") as f:
    data = tomllib.load(f)
print(data)

try:
    with open("app.toml") as f:
        tomllib.load(f)
except TypeError as e:
    print("TypeError:", e)
Text
{'name': 'web', 'ports': [8080, 8081], 'db': {'host': 'localhost'}}
TypeError: File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`

tomllib.load takes a file object opened in binary mode, because TOML is defined as UTF-8 and the parser does the decoding itself. Opening it in text mode raises a TypeError that says so, as the last line of output shows. Tables become dictionaries and arrays become lists. The module is documented in the Python library reference and was added in 3.11.

The module only reads. Writing TOML needs a third-party package such as tomli-w. Dates and times become datetime objects, and integers keep their exact value, while a malformed file raises tomllib.TOMLDecodeError with the line and column. On Python 3.10 and older, install tomli, which has the same interface.

Taggedpython
Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.