objectif
Remplacer (move) atomiquement un fichier s’il existe déjà.
code minimal
import os, tempfile, pathlib
with tempfile.TemporaryDirectory() as tmp:
p = pathlib.Path(tmp)/"a.txt"; q = pathlib.Path(tmp)/"b.txt"
p.write_text("v1", encoding="utf-8")
os.replace(p, q)
print(q.read_text(encoding="utf-8") == "v1") # attendu: True
utilisation
import os, tempfile, pathlib
with tempfile.TemporaryDirectory() as tmp:
dst = pathlib.Path(tmp)/"f.txt"; dst.write_text("old", encoding="utf-8")
tmpf = pathlib.Path(tmp)/"f.tmp"; tmpf.write_text("new", encoding="utf-8")
os.replace(tmpf, dst) # swap atomique
print(dst.read_text(encoding="utf-8") == "new")
variante(s) utile(s)
import os.path
print(callable(os.replace))
notes
- Atomique sur la même partition (même filesystem).
- Utilisez-le après fsync sur le fichier temporaire pour écriture sûre.