← retour aux snippets

tarfile: lister le contenu sans extraction

Inspecter les membres d'une archive .tar(.gz/.xz) sans l'extraire.

python archive #tarfile#list#inspect

objectif

Inspecter les membres d’une archive .tar(.gz/.xz) sans l’extraire.

code minimal

import tarfile, io
data = io.BytesIO()
with tarfile.open(fileobj=data, mode="w:gz") as tf:
    info = tarfile.TarInfo("a.txt"); info.size = 1
    tf.addfile(info, io.BytesIO(b"x"))
data.seek(0)
with tarfile.open(fileobj=data, mode="r:gz") as tf:
    names = [m.name for m in tf.getmembers()]
    print("a.txt" in names)  # attendu: True

utilisation

import tarfile, io
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as tf:
    t = tarfile.TarInfo("b.dat"); t.size = 2; tf.addfile(t, io.BytesIO(b"yy"))
buf.seek(0)
with tarfile.open(fileobj=buf, mode="r") as tf:
    print(any(m.size == 2 for m in tf.getmembers()))

variante(s) utile(s)

import tarfile
print(hasattr(tarfile, "TarInfo"))

notes

  • Préférez getmembers()/getnames() pour un aperçu rapide.
  • Pour de très grosses archives, itérez avec getmembers() paresseusement via next().