ZetCode

Python TOML

last modified November 19, 2026 Python 3.15

In this article we show how to write and edit TOML files in Python. Reading TOML with the standard tomllib module is covered in the Python tomllib article; here we only use it to check what we have written.

TOML format

TOML (Tom's Obvious Minimal Language) is a configuration file format designed to be easy to read and to map unambiguously to a dictionary. It has key/value pairs, tables (sections in square brackets), arrays, inline tables, arrays of tables, strings, integers, floats, booleans, and dates and times. Files have the .toml extension. The best-known TOML file in the Python world is pyproject.toml.

The standard library can read TOML since Python 3.11, and since Python 3.15 tomllib supports TOML 1.1. It cannot write TOML. For writing there are two third-party libraries: tomli-w, the write-only counterpart of tomllib, and tomlkit, which keeps comments and formatting when a file is edited. The examples use tomli-w 1.2 and tomlkit 0.15.

$ pip install tomli-w tomlkit

Reading a file

Before we write anything, a short reminder of how a TOML file is read. We use the following configuration file in several examples.

config.toml
# Application settings
title = "Inventory"
debug = false

[server]
host = "127.0.0.1"
port = 8080  # development port

[database]
url = "sqlite:///inventory.db"
pool = 5

The file has two top-level keys, a server table, and a database table. Lines starting with # are comments, and a comment may also follow a value.

read_config.py
import tomllib

with open('config.toml', 'rb') as f:
    config = tomllib.load(f)

print(config)
print(config['server']['port'])
print(type(config['debug']))

The tomllib.load function needs a file opened in binary mode and returns a dictionary; tables become nested dictionaries. The comments are dropped.

$ python read_config.py
{'title': 'Inventory', 'debug': False, 'server': {'host': '127.0.0.1', 'port': 8080}, 'database': {'url': 'sqlite:///inventory.db', 'pool': 5}}
8080
<class 'bool'>

Writing a string

The tomli_w.dumps function converts a dictionary to a TOML string.

write_string.py
import tomli_w

config = {
    'title': 'Inventory',
    'debug': False,
    'server': {'host': '127.0.0.1', 'port': 8080},
    'tags': ['shop', 'stock'],
}

text = tomli_w.dumps(config)
print(text, end="")

Simple values are written first and nested dictionaries become tables after them, because a key placed after a table header would belong to that table. Arrays are written one item per line with a trailing comma, which TOML allows. The string ends with a newline, hence end=''.

$ python write_string.py
title = "Inventory"
debug = false
tags = [
    "shop",
    "stock",
]

[server]
host = "127.0.0.1"
port = 8080

Writing a file

The tomli_w.dump function writes to a file. Like tomllib.load, it works with binary files, and the output is always UTF-8.

write_file.py
import tomllib
import tomli_w

settings = {
    'name': 'backup',
    'retention_days': 14,
    'paths': {'source': '/srv/data', 'target': '/mnt/backup'},
}

with open('backup.toml', 'wb') as f:
    tomli_w.dump(settings, f)

with open('backup.toml', 'rb') as f:
    print(tomllib.load(f) == settings)

with open('backup.toml', encoding='utf-8') as f:
    print(f.read())

We write the settings, read the file back with tomllib, and compare the result with the original dictionary. The round trip gives equal data. Opening the file in text mode for dump would raise a TypeError, because it writes bytes.

$ python write_file.py
True
name = "backup"
retention_days = 14

[paths]
source = "/srv/data"
target = "/mnt/backup"

Value types

TOML has native types for dates and times, so tomli-w can write datetime objects without converting them to strings.

write_types.py
import datetime as dt
from decimal import Decimal

import tomli_w

data = {
    'release': dt.date(2026, 11, 19),
    'build': dt.datetime(2026, 11, 19, 9, 30, tzinfo=dt.timezone.utc),
    'backup_at': dt.time(2, 0),
    'ratio': 0.75,
    'price': Decimal('19.90'),
    'size': (1920, 1080),
}

print(tomli_w.dumps(data), end='')

A date becomes a local date, an aware datetime an offset date-time, and a time a local time. A Decimal keeps its digits, including the trailing zero, but tomllib reads it back as a float unless parse_float=Decimal is given. Tuples are written as arrays.

$ python write_types.py
release = 2026-11-19
build = 2026-11-19 09:30:00+00:00
backup_at = 02:00:00
ratio = 0.75
price = 19.90
size = [
    1920,
    1080,
]

Tables and arrays of tables

Nested dictionaries become tables, and a list of dictionaries becomes an array of tables. tomli-w chooses the layout by itself.

write_tables.py
import tomli_w

data = {
    'database': {
        'primary': {'host': 'db1', 'port': 5432},
        'replica': {'host': 'db2', 'port': 5432},
    },
    'users': [
        {'name': 'alice', 'admin': True},
        {'name': 'bob', 'admin': False},
    ],
    'jobs': [
        {'name': 'backup', 'cron': '0 2 * * *', 'paths': ['/etc', '/srv']},
        {'name': 'cleanup', 'cron': '30 3 * * 0', 'paths': ['/tmp']},
    ],
}

print(tomli_w.dumps(data), end='')

The database dictionary holds only other dictionaries, so tomli-w writes the dotted headers [database.primary] and [database.replica] and no empty [database] table. For a list of dictionaries, it writes inline tables when every item fits on one line of at most 100 characters without line breaks; the jobs items contain multiline arrays, so they become [[jobs]] sections. Both forms read back as a list of dictionaries.

$ python write_tables.py
users = [
    { name = "alice", admin = true },
    { name = "bob", admin = false },
]

[database.primary]
host = "db1"
port = 5432

[database.replica]
host = "db2"
port = 5432

[[jobs]]
name = "backup"
cron = "0 2 * * *"
paths = [
    "/etc",
    "/srv",
]

[[jobs]]
name = "cleanup"
cron = "30 3 * * 0"
paths = [
    "/tmp",
]

Unsupported values

TOML has no null value and its keys are always strings. tomli-w raises a TypeError for data it cannot represent.

write_errors.py
import tomli_w

samples = [
    {'timeout': None},
    {1: 'one'},
    {'ids': {1, 2, 3}},
]

for data in samples:
    try:
        tomli_w.dumps(data)
    except TypeError as e:
        print(e)

clean = {k: v for k, v in {'host': 'db', 'port': None}.items() if v is not None}
print(tomli_w.dumps(clean), end='')

None, an integer key, and a set all fail. The usual fix for None is to leave the key out, as done for port in the last line; a reader then falls back to a default. A set must be converted to a sorted list first.

$ python write_errors.py
Object of type 'NoneType' is not TOML serializable
Invalid mapping key '1' of type 'int'. A string is required.
Object of type 'set' is not TOML serializable
host = "db"

Output options

The dumps and dump functions have two keyword options: multiline_strings and indent.

write_options.py
import tomli_w

data = {
    'motd': 'Welcome!\nMaintenance on Sunday.',
    'ports': [8080, 8081],
}

print(tomli_w.dumps(data), end='')
print('-' * 20)
print(tomli_w.dumps(data, multiline_strings=True, indent=2), end='')

By default a newline in a string is written as the \n escape. With multiline_strings=True, such strings are written as multiline basic strings in triple quotes. The indent option sets the indentation of array items, four spaces by default.

$ python write_options.py
motd = "Welcome!\nMaintenance on Sunday."
ports = [
    8080,
    8081,
]
--------------------
motd = """
Welcome!
Maintenance on Sunday."""
ports = [
  8080,
  8081,
]

Comments are lost

Reading a file with tomllib, changing a value, and writing it with tomli-w is a correct round trip of the data, but not of the file.

lost_comments.py
import tomllib
import tomli_w

with open('config.toml', 'rb') as f:
    config = tomllib.load(f)

config['server']['port'] = 9000

print(tomli_w.dumps(config), end='')

The port is changed, but both comments from config.toml are gone, and the file would be reformatted. That is fine for files a program owns, but not for files edited by people, such as pyproject.toml.

$ python lost_comments.py
title = "Inventory"
debug = false

[server]
host = "127.0.0.1"
port = 9000

[database]
url = "sqlite:///inventory.db"
pool = 5

Editing with tomlkit

The tomlkit library parses TOML into a document object that remembers comments, whitespace, and the order of items. The document behaves like a dictionary, and tomlkit.dumps writes it back unchanged except for our edits.

tomlkit_edit.py
import tomlkit

with open('config.toml', encoding='utf-8') as f:
    doc = tomlkit.parse(f.read())

print(doc['server']['port'], type(doc['server']['port']))

doc['server']['port'] = 9000
doc['debug'] = True
doc['database']['timeout'] = 30

print(tomlkit.dumps(doc), end='')

Values in the document are tomlkit items; the port is a tomlkit.items.Integer, a subclass of int, so it can be used as a number. We change two values and add a new key to the database table. The comments and the spacing of the original file are kept, including the comment after the port.

$ python tomlkit_edit.py
8080 <class 'tomlkit.items.Integer'>
# Application settings
title = "Inventory"
debug = true

[server]
host = "127.0.0.1"
port = 9000  # development port

[database]
url = "sqlite:///inventory.db"
pool = 5
timeout = 30

Building a document

tomlkit can also create a document from scratch, with control over comments, blank lines, and the style of each value.

tomlkit_build.py
import tomlkit

doc = tomlkit.document()
doc.add(tomlkit.comment('Generated by deploy.py'))
doc.add(tomlkit.nl())
doc['environment'] = 'production'

server = tomlkit.table()
server['host'] = '0.0.0.0'
server['port'] = 443
server['port'].comment('HTTPS')
doc['server'] = server

hosts = tomlkit.array()
hosts.extend(['web1.example.com', 'web2.example.com'])
hosts.multiline(True)
doc['server']['allowed_hosts'] = hosts

limits = tomlkit.inline_table()
limits.update({'rps': 100, 'burst': 20})
doc['limits'] = limits

print(tomlkit.dumps(doc), end='')

The comment and nl functions add a comment line and an empty line. The comment method of an item adds a comment after the value. A tomlkit.array with multiline(True) is written one item per line and an inline_table stays on one line. tomlkit places the inline limits table before the [server] table, because after the header it would become part of server.

$ python tomlkit_build.py
# Generated by deploy.py

environment = "production"
limits = {rps = 100, burst = 20}

[server]
host = "0.0.0.0"
port = 443 # HTTPS
allowed_hosts = [
    "web1.example.com",
    "web2.example.com",
]

Arrays of tables in tomlkit

An array of tables in a tomlkit document behaves like a list of tables. The unwrap method converts the whole document to plain Python objects.

tomlkit_aot.py
import tomlkit

doc = tomlkit.parse('''\
[[plugins]]
name = "auth"   # required
enabled = true

''')

plugin = tomlkit.table()
plugin['name'] = 'cache'
plugin['enabled'] = False
doc['plugins'].append(plugin)

print(tomlkit.dumps(doc))
print(len(doc['plugins']), [p['name'] for p in doc['plugins']])

plain = doc.unwrap()
print(plain)
print(type(plain['plugins'][0]['name']))

We append a new table to the plugins array and tomlkit writes it as another [[plugins]] section. The comment after the first name is kept. The unwrap method returns ordinary dictionaries, lists, and strings, which is useful when the data is passed to code that does not expect tomlkit types.

$ python tomlkit_aot.py
[[plugins]]
name = "auth"   # required
enabled = true

[[plugins]]
name = "cache"
enabled = false

2 ['auth', 'cache']
{'plugins': [{'name': 'auth', 'enabled': True}, {'name': 'cache', 'enabled': False}]}
<class 'str'>

Updating pyproject.toml

The last program bumps the version in a pyproject.toml file and adds a dependency, keeping the rest of the file as it was.

pyproject.toml
[project]
name = "inventory"
version = "1.4.2"
requires-python = ">=3.12"
dependencies = [
    "httpx>=0.28",   # HTTP client
    "rich>=14",
]

[tool.ruff]
line-length = 88

This is the project file. The dependency array has a comment that must survive the update.

bump_project.py
import sys

import tomlkit

def bump(version, part):
    major, minor, patch = map(int, version.split('.'))
    match part:
        case 'major': return f'{major + 1}.0.0'
        case 'minor': return f'{major}.{minor + 1}.0'
        case 'patch': return f'{major}.{minor}.{patch + 1}'
    raise ValueError(f'unknown part: {part}')

def add_dependency(deps, spec):
    name = spec.split('>')[0].split('=')[0].strip()
    for dep in deps:
        if dep.split('>')[0].split('=')[0].strip() == name:
            sys.exit(f'{name} is already a dependency')
    deps.append(spec)

with open('pyproject.toml', encoding='utf-8') as f:
    doc = tomlkit.parse(f.read())

project = doc['project']
old = project['version']
project['version'] = bump(old, 'minor')
add_dependency(project['dependencies'], 'tomlkit>=0.13')

with open('pyproject.toml', 'w', encoding='utf-8') as f:
    f.write(tomlkit.dumps(doc))

print(f'version {old} -> {project["version"]}')
with open('pyproject.toml', encoding='utf-8') as f:
    print(f.read(), end='')

The bump function increases one part of a semantic version with a match statement. The add_dependency function compares package names without version specifiers and refuses to add a package twice. The dependency array behaves like a list, so we append to it and tomlkit keeps its multiline layout and the comment. The file is written in text mode, because tomlkit.dumps returns a string.

$ python bump_project.py
version 1.4.2 -> 1.5.0
[project]
name = "inventory"
version = "1.5.0"
requires-python = ">=3.12"
dependencies = [
    "httpx>=0.28",   # HTTP client
    "rich>=14",
    "tomlkit>=0.13",
]

[tool.ruff]
line-length = 88

Source

TOML specification

tomli-w on GitHub

tomlkit documentation

In this article we have written TOML files with tomli-w and edited them with tomlkit. See also Python tomllib for reading TOML, Python YAML, and Python configparser.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.