objectif
Copier un fichier en conservant mtime, mode, et autres attributs.
code minimal
import shutil, tempfile, pathlib, time
with tempfile.TemporaryDirectory() as tmp:
src = pathlib.Path(tmp)/"a"; dst = pathlib.Path(tmp)/"b"
src.write_text("x", encoding="utf-8")
out = shutil.copy2(src, dst)
print(out.endswith("b") and dst.exists()) # attendu: True
utilisation
import shutil, tempfile, pathlib
with tempfile.TemporaryDirectory() as tmp:
p = pathlib.Path(tmp)/"x"; p.write_text("data")
q = pathlib.Path(tmp)/"y"
shutil.copy2(p, q)
print(q.stat().st_size == p.stat().st_size)
variante(s) utile(s)
import shutil
print(hasattr(shutil, "copy2"))
notes
- copy2 tente de préserver autant de metadata que possible.
- Entre filesystems/OS différents, certaines métadonnées peuvent ne pas se copier.