TOML Kit is a style-preserving TOML library for Python, currently at version 0.14.0. It offers a parser that maintains comments, indentations, whitespace, and internal element ordering, providing an intuitive API for accessing and editing TOML files. The library is actively maintained with regular updates, as seen in its recent releases.
pip install tomlkitVerified import paths — ran on the pinned version, not inferred.
A quickstart guide demonstrating parsing, modifying, and writing TOML documents using TOML Kit.
Upgrade to TOML Kit version 0.13.0 or later.
Use 'parse' instead of 'loads' for parsing TOML strings.
Use TOML Kit's API methods for modifications to maintain style preservation.
It is recommended to use a virtual environment for pip operations and consider upgrading pip as suggested in the notice.
Install the tomlkit library using pip: `pip install tomlkit`
Convert the TOMLDocument to a string using `tomlkit.dumps()` or `str()` before writing it to a file:
```python
import tomlkit
doc = tomlkit.document()
doc["example"] = "value"
# To write to a file
with open("config.toml", "w") as f:
f.write(tomlkit.dumps(doc))
# Or using str()
# with open("config.toml", "w") as f:
# f.write(str(doc))
```Ensure that intermediate TOML tables (sections) are created as `tomlkit.table()` objects before trying to set keys within them: ```python import tomlkit doc = tomlkit.document() # Correct way to create nested sections doc["server"] = tomlkit.table() doc["server"]["port"] = 8080 # If you want to add keys to an existing table or create a new one within it doc["database"] = tomlkit.table() doc["database"]["connection"] = tomlkit.table() doc["database"]["connection"]["url"] = "localhost:5432" ```