← retour aux snippets

tempfile: répertoire temporaire sûr

Créer un dossier éphémère isolé et le nettoyer automatiquement.

python filesystem #tempfile#filesystem#io

objectif

Créer un dossier éphémère isolé et le nettoyer automatiquement.

code minimal

import os
from tempfile import TemporaryDirectory

with TemporaryDirectory() as tmp:
    f = os.path.join(tmp, "x.txt")
    with open(f, "w", encoding="utf-8") as fh:
        fh.write("ok\n")
    print(os.path.exists(f))  # attendu: True

utilisation

from tempfile import gettempdir
print(isinstance(gettempdir(), str))

variante(s) utile(s)

import tempfile, pathlib
d = pathlib.Path(tempfile.mkdtemp(prefix="job-"))
print(d.exists() and d.is_dir())

notes

  • TemporaryDirectory supprime le dossier à la sortie du contexte.
  • Préfixez pour aider au debug des jobs éphémères.