zip.py
1 """ 2 Zip module 3 """ 4 5 import os 6 7 from zipfile import ZipFile, ZIP_DEFLATED 8 9 from .compress import Compress 10 11 12 class Zip(Compress): 13 """ 14 Zip compression 15 """ 16 17 def pack(self, path, output): 18 with ZipFile(output, "w", ZIP_DEFLATED) as zfile: 19 for root, _, files in sorted(os.walk(path)): 20 for f in files: 21 # Generate archive name with relative path, if necessary 22 name = os.path.join(os.path.relpath(root, path), f) 23 24 # Write file to zip 25 zfile.write(os.path.join(root, f), arcname=name) 26 27 def unpack(self, path, output): 28 with ZipFile(path, "r") as zfile: 29 # Validate paths if directory specified 30 for fullpath in zfile.namelist(): 31 fullpath = os.path.join(path, fullpath) 32 if os.path.dirname(fullpath) and not self.validate(path, fullpath): 33 raise IOError(f"Invalid zip entry: {fullpath}") 34 35 # Unpack data 36 zfile.extractall(output)