tomledit
tomledit is a Python library designed for parsing and editing TOML files while meticulously preserving comments, whitespace, and the original order of elements. It is especially useful for managing configuration files where maintaining human-readable formatting is critical. The current version is 1.1.0, and it is actively maintained with releases made as needed.
Common errors
-
ModuleNotFoundError: No module named 'tomledit'
cause The 'tomledit' package has not been installed in your current Python environment.fixInstall the library using pip: `pip install tomledit` -
TomlEditError: Unexpected token '...' at line X, column Y
cause The input TOML string provided to `TomlDocument.parse()` or the file loaded by `TomlDocument.load()` contains syntax errors and is not valid TOML.fixReview the TOML input at the specified line and column for syntax errors. `tomledit` requires valid TOML for parsing, even if its goal is to preserve formatting during edits. -
My comments are gone after modifying a TOML value!
cause This typically occurs if you use non-format-preserving dictionary methods (like `pop()`) on a `TomlDocument` object, which removes the entire node including its comments. It can also happen if you print the document to a string and then re-parse that string, as some default string representations may not perfectly capture all formatting.fixEnsure all modifications are done directly on the `TomlDocument` object using item assignment (`doc['key'] = new_value`) to preserve associated comments. Avoid `pop()` for modifications where comments must be retained. If saving to a file, use `doc.dump(file_object)`.
Warnings
- gotcha tomledit prioritizes format preservation for *existing* documents. When creating a new document entirely from a dictionary using `TomlDocument.from_dict()`, the resulting TOML string's formatting (e.g., indentation, spacing, table order) will use default styles and is not highly configurable to match specific aesthetic preferences.
- gotcha While `TomlDocument` mimics dictionary behavior, not all dictionary operations are fully format-preserving. Methods like `pop()`, `clear()`, or direct list manipulation (for arrays of tables) can lead to loss of associated comments or specific whitespace for the affected sections.
- gotcha tomledit parses TOML 1.0.0. While robust, feeding it significantly malformed TOML will raise a `TomlEditError`. It's an editor designed to work with valid TOML, not a parser designed to recover from arbitrary syntax errors.
Install
-
pip install tomledit
Imports
- TomlDocument
from tomledit import TomlDocument
- TomlEditError
from tomledit import TomlEditError
Quickstart
from tomledit import TomlDocument
toml_content = """
# Main config
[server]
host = "localhost" # Server IP
port = 8080
[database]
type = "PostgreSQL"
user = "admin"
"""
# Parse the TOML content
doc = TomlDocument.parse(toml_content)
print("--- Original Document ---")
print(doc)
# Modify values, preserving comments and format
doc["server"]["host"] = "127.0.0.1"
doc["database"]["user"] = "dbuser"
# Add a new key to an existing table
doc["database"]["password"] = "securepassword"
print("\n--- Modified Document ---")
print(doc)