When reading or writing pyproject.toml or .toml config files in Python. When editing TOML while preserving comments and formatting. When designing configuration file format for a Python tool. When code uses tomlkit or tomllib. When implementing atomic config file updates.
Work with TOML configuration files using the tomlkit library, which preserves comments and formatting during read-modify-write cycles.
Use this skill when:
Use tomlkit when:
Use tomllib (stdlib) when:
For config file management, tomlkit is the recommended choice.
# Using uv (recommended)
uv add tomlkit
# Using pip
pip install tomlkit
Requirements: Python >=3.8, tomlkit >=0.12.0
import tomlkit
# From string
doc = tomlkit.parse(toml_string)
doc = tomlkit.loads(toml_string) # Alias for parse()
# From file object
with open('config.toml', 'r') as f:
doc = tomlkit.load(f)
# Using TOMLFile class (convenient)
from tomlkit import TOMLFile
toml_file = TOMLFile('config.toml')
doc = toml_file.read()
Returns: TOMLDocument object (dict-like, preserves formatting)
import tomlkit
# To string
toml_string = tomlkit.dumps(data)
# To file object
with open('config.toml', 'w') as f:
tomlkit.dump(data, f)
# Using TOMLFile class
from tomlkit import TOMLFile
toml_file = TOMLFile('config.toml')
toml_file.write(doc)
from tomlkit import document, table, comment, nl, array, inline_table
# Create document
doc = document()
doc.add(comment("Configuration file"))
doc.add(nl())
doc.add("title", "My Config")
# Create table
db_config = table()
db_config["host"] = "localhost"
db_config["port"] = 5432
doc["database"] = db_config
# Create inline table
point = inline_table()
point.update({'x': 1, 'y': 2})
doc["point"] = point
# Create array
numbers = array()
numbers.extend([1, 2, 3])
doc["numbers"] = numbers
# Dict-like access
doc["section"]["key"] = "value"
value = doc["section"]["key"]
# Get with default
value = doc.get("key", "default")
# Check existence
if "key" in doc:
pass
# Iterate
for key, value in doc.items():
print(key, value)
# Remove key
doc.pop("key")
doc.remove("key")
# Convert to pure Python dict
pure_dict = doc.unwrap()
# Get as TOML string
toml_str = doc.as_string()
from tomlkit import (
item, # Auto-detect type
string, # String with options
integer, # Integer
float_, # Float
boolean, # Boolean
datetime, # Datetime
date, # Date
time, # Time
)
# Auto-detect type
doc["key"] = item(42)
doc["key"] = item([1, 2, 3])
doc["key"] = item({'nested': 'table'})
# Explicit string types
doc["basic"] = string("text")
doc["literal"] = string("text", literal=True) # Single quotes
doc["multiline"] = string("line1\nline2", multiline=True)
from tomlkit.exceptions import (
TOMLKitError, # Base exception
ParseError, # Syntax errors (has .line and .col)
NonExistentKey, # Missing key access
KeyAlreadyPresent, # Duplicate key
ConvertError, # Type conversion failure
)
# Handle parse errors