unzip

pyhelpers.store.unzip(zip_file_path, output_dir=None, return_output_dir=False, verbose=False, raise_error=False, **kwargs)[source]

Unzip data from a Zip (compressed) file.

This function extracts all contents of a Zip archive to a specified directory. If no output directory is provided, a directory named after the Zip file (without extension) is created in the same location.

Parameters:
  • zip_file_path (str | pathlib.Path | os.PathLike) – Path where the Zip file is saved.

  • output_dir (str | pathlib.Path | None) – Directory where extracted data will be saved. Defaults to None.

  • return_output_dir (bool) – Whether to return the path to the output directory. Defaults to False.

  • verbose (bool | int) – Whether to print relevant information to the console. Defaults to False.

  • raise_error (bool) – Whether to raise an exception on failure. Defaults to False.

  • kwargs – [Optional] Additional parameters for the method zipfile.ZipFile.extractall().

Examples:

>>> from pyhelpers.store import unzip
>>> from pyhelpers.dirs import cd, delete_dir

>>> zip_file_path = cd("tests/data", "dat.zip")
>>> unzip(zip_file_path, verbose=True)
Extracting "tests/data/dat.zip" to "tests/data/dat/" ... Done.

>>> output_dir_1 = cd("tests/data", "dat")
>>> out_file_pathname = cd(output_dir_1, "zipped.txt")
>>> with open(out_file_pathname) as f:
...     print(f.read())
test

>>> output_dir_2 = cd("tests/data", "dat_alt")
>>> unzip(zip_file_path, output_dir=output_dir_2, verbose=True)
Extracting "tests/data/dat.zip" to "tests/data/dat_alt/" ... Done.
>>> out_file_pathname = cd(output_dir_2, "zipped.txt")
>>> with open(out_file_pathname) as f:
...     print(f.read())
test

>>> # Delete the directories "tests/data/dat/" and "tests/data/dat_alt/"
>>> delete_dir([output_dir_1, output_dir_2], verbose=True)
Confirm deletion of the following directories:
  "tests/data/dat/" (Not empty)
  "tests/data/dat_alt/" (Not empty)
? [No]|Yes: yes
Deleting:
  "tests/data/dat/" ... Done.
  "tests/data/dat_alt/" ... Done.