Skip to content

Instantly share code, notes, and snippets.

@NicolasPA
Last active April 8, 2022 17:03
Show Gist options
  • Save NicolasPA/7e77a035ba59de8a35e9d310a73780a9 to your computer and use it in GitHub Desktop.
Save NicolasPA/7e77a035ba59de8a35e9d310a73780a9 to your computer and use it in GitHub Desktop.
Unzip archive recursively
import zipfile
from typing import Dict, Union, IO
from io import BytesIO
from zipfile import ZipFile
def unzip_recursively(archive_path: Union[str, IO[bytes]]) -> Dict[str, BytesIO]:
"""
Unzip archive recursively
:param archive_path: path to the zip archive
:return: Dictionary with file name as key and file bytes as value
"""
def _unzip_recursively(
_archive_path: Union[str, IO[bytes]], _files_data: Dict[str, bytes] = None
) -> Dict[str, BytesIO]:
"""Private function to hide _files_data parameter only useful for the recursion."""
if _files_data is None:
_files_data = {}
with ZipFile(_archive_path, "r") as zipped_archive:
for file_name in zipped_archive.namelist():
try:
_unzip_recursively(zipped_archive.open(file_name, "r"), _files_data)
except zipfile.BadZipFile: # not a zip file, we can open
_files_data[file_name] = BytesIO(
zipped_archive.open(file_name, "r").read()
)
return _files_data
return _unzip_recursively(archive_path)
archive_path1 = "my/archive.zip"
unzipped_dict = unzip_recursively(archive_path1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment