Python Tomllib Modul
Das tomllib-Modul parst TOML-Konfigurationsdateien in Python.
Das Modul wurde in Python 3.11 hinzugefügt. Es ist schreibgeschützt, verwende es also zum Parsen von TOML und nicht zum Schreiben.
import tomllib
TOML wird häufig für Konfigurationsdateien wie pyproject.toml verwendet. Es sieht aus wie einfache Schlüssel-Wert-Paare und Abschnitte.
TOML aus einem String parsen
loads parst ein TOML-Dokument, das in einem String gespeichert ist.
import tomllib
config = tomllib.loads("""
name = "python-cheatsheet"
version = "1.0"
[database]
port = 5432
""")
print(config['name'])
print(config['database']['port'])
python-cheatsheet
5432
TOML-Werte werden in Python-Werte umgewandelt:
import tomllib
config = tomllib.loads("""
debug = true
ports = [8000, 8001]
""")
print(config['debug'])
print(config['ports'])
True
[8000, 8001]
Eine TOML-Datei lesen
load erwartet ein binäres Dateiobjekt.
import tomllib
from io import BytesIO
data = b'name = "demo"'
config = tomllib.load(BytesIO(data))
print(config)
{'name': 'demo'}
Wenn du eine echte Datei öffnest, verwende den Binärmodus:
import tomllib
with open('pyproject.toml', 'rb') as file:
config = tomllib.load(file)