Tomli-W: A Minimal TOML Writer

1.2.0 · active · verified Sun Mar 29

Tomli-W is a pure Python library designed for writing TOML (Tom's Obvious, Minimal Language) documents. It acts as the write-only counterpart to the `tomli` parser (which is also the basis for the `tomllib` standard library module in Python 3.11+). It is fully compatible with TOML v1.0.0 and focuses on simplicity and correctness in output. The library maintains an active status with periodic updates.

Warnings

Install

Imports

Quickstart

This example demonstrates how to write a Python dictionary to a TOML formatted string using `tomli_w.dumps()` and how to write it directly to a file using `tomli_w.dump()`. It includes a cleanup step to remove the generated file.

import tomli_w
import os

# Example data to write
doc = {
    "title": "My Awesome Project",
    "owner": {
        "name": "Alice Example",
        "organization": "Example Corp",
        "dob": "1979-05-27T07:32:00-08:00"
    },
    "database": {
        "server": "192.168.1.1",
        "ports": [8001, 8001, 8002],
        "connection_max": 5000,
        "enabled": True
    },
    "servers": {
        "alpha": {
            "ip": "10.0.0.1",
            "dc": "eqdc10"
        },
        "beta": {
            "ip": "10.0.0.2",
            "dc": "eqdc10"
        }
    }
}

# 1. Write to a string
toml_string = tomli_w.dumps(doc)
print("--- TOML String ---")
print(toml_string)

# 2. Write to a file
file_path = "config.toml"
try:
    with open(file_path, "wb") as f:
        tomli_w.dump(doc, f)
    print(f"\n--- TOML written to {file_path} ---")
    with open(file_path, "r") as f_read:
        print(f_read.read())
except Exception as e:
    print(f"Error writing TOML to file: {e}")
finally:
    if os.path.exists(file_path):
        os.remove(file_path) # Clean up

view raw JSON →