← retour aux snippets

tarfile: archive .tar.xz simple

Créer une archive tar compressée en xz et l'extraire.

python compression #tar#xz#archive

objectif

Créer une archive tar compressée en xz et l’extraire.

code minimal

import tarfile
from tempfile import TemporaryDirectory
from pathlib import Path

with TemporaryDirectory() as tmp:
    root = Path(tmp)
    (root / "data").mkdir()
    (root / "data" / "x.txt").write_text("X\n", encoding="utf-8")
    tar_path = root / "data.tar.xz"
    with tarfile.open(tar_path, "w:xz") as t:
        t.add(root / "data", arcname="data")
    with tarfile.open(tar_path, "r:xz") as t:
        t.extractall(root / "out")
    print((root / "out" / "data" / "x.txt").read_text().strip())  # attendu: X

utilisation

import tarfile, io
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as t:
    info = tarfile.TarInfo("x.txt"); info.size = 0
    t.addfile(info)
print(buf.getbuffer().nbytes > 0)

variante(s) utile(s)

import tarfile, io
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as t:
    t.addfile(tarfile.TarInfo("empty/"))
print(buf.getbuffer().nbytes > 0)

notes

  • Modes: “w”, “w:gz”, “w:bz2”, “w:xz” selon le codec disponible.
  • Attention aux chemins absolus et symlinks lors de l’extraction.