← retour aux snippets

zipfile.Path: parcourir une archive comme un système de fichiers

Lire des fichiers à l'intérieur d'un zip via une API de type Path.

python archive #zipfile#traversable

objectif

Lire des fichiers à l’intérieur d’un zip via une API de type Path.

code minimal

import zipfile, io
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
    z.writestr("dir/a.txt", "hi")
zp = zipfile.Path(buf, at="dir")
print(any(p.name == "a.txt" for p in zp.iterdir()))  # attendu: True

utilisation

import zipfile, io
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
    z.writestr("x.txt", "ok")
zp = zipfile.Path(buf, at="")
with zp.joinpath("x.txt").open("r") as f:
    print(f.read() == "ok")

variante(s) utile(s)

import zipfile
print(hasattr(zipfile, "Path"))

notes

  • zipfile.Path évite d’extraire pour explorer/consulter des entrées.
  • Parfait pour des inspections rapides d’archives.