objectif
Manipuler des chemins et du texte de manière portable et lisible.
code minimal
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
p = Path(tmp) / "hello.txt"
p.write_text("bonjour\n", encoding="utf-8")
content = p.read_text(encoding="utf-8")
print(content.strip()) # attendu: bonjour
utilisation
from pathlib import Path
home = Path.home()
cfg = home / ".config" / "app" / "config.ini"
print(str(cfg).endswith("config.ini"))
variante(s) utile(s)
from pathlib import Path
p = Path("logs") / "app.log"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(b"ok\n")
print(p.exists() and p.stat().st_size > 0)
notes
- Préférez pathlib à os.path pour un code plus lisible et portable.
- Toujours fixer encoding explicite pour du texte.