← retour aux snippets

pathlib.touch: créer un fichier et mettre à jour mtime

Créer le fichier s'il n'existe pas et rafraîchir son horodatage.

python filesystem #pathlib#touch#mtime

objectif

Créer le fichier s’il n’existe pas et rafraîchir son horodatage.

code minimal

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
    p = Path(tmp) / "test.txt"
    p.touch(exist_ok=True)
    print(p.exists() and p.is_file())  # attendu: True

utilisation

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
    p = Path(tmp) / "a.log"
    p.touch()
    old = p.stat().st_mtime
    p.touch()  # rafraîchit mtime
    print(p.stat().st_mtime >= old)

variante(s) utile(s)

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tmp:
    p = Path(tmp) / "x/y/z.txt"
    p.parent.mkdir(parents=True, exist_ok=True)
    p.touch()
    print(p.parent.exists())

notes

  • touch(exist_ok=True) évite l’exception si le fichier existe.
  • Combinez avec mkdir(parents=True) pour créer l’arborescence.