stouputils.archive package#

This module provides functions for creating and managing archives.

  • repair_zip_file() - Try to repair a corrupted zip file by ignoring some of the errors

  • make_archive() - Create a zip archive from a source directory with consistent file timestamps.

  • archive_cli() - Main entry point for command line usage

import zipfile
from pathlib import Path
import stouputils as stp

# Create a folder with 50 small text files
for index in range(50):
        stp.super_open(f"project/notes/note_{index}.txt", "w").write(f"Note {index}. " * 500)

# Zip the folder
stp.make_archive("project", "project.zip")

# Keep only the first two thirds of the zip, like an interrupted download
content = Path("project.zip").read_bytes()
two_thirds = len(content) * 2 // 3
Path("partial.zip").write_bytes(content[:two_thirds])

# Python's zipfile refuses to open it
try:
        zipfile.ZipFile("partial.zip")
except zipfile.BadZipFile as error:
        stp.warning("zipfile cannot open partial.zip:", error)

# stouputils still recovers the files it can read
stp.repair_zip_file("partial.zip", "repaired.zip")
recovered_files = zipfile.ZipFile("repaired.zip").namelist()
stp.info("Recovered", len(recovered_files), "of 50 files")
Terminal output of the example, the truncated archive failing to open then being repaired

Subpackages#

Submodules#