""" Description: Module to zippping up assets. Author: Mark Harrison-Ball Usage: import RS.Utils.ZipAssets as zipUtils zipUtils.zipAssets("x:/gta5_dlc/mpPacks/mpHeist/assets/cuts/MPH_NAR_FIN_EXT_P4_L1_P3") """ import os import shutil import zipfile import cStringIO def _zipdir(zipFile, path, basePath=""): """ Add contents of our directory to the zip file """ basePath = basePath.rstrip("\\/") for root, dirs, files in os.walk(path): for file in files: filePath = os.path.join(root, file) inZipPath = filePath.replace(basePath, "", 1).lstrip("\\/") zipFile.write(filePath, inZipPath) def zipAssets(filepath, zip_filename = None): """ Basic Zip file/folder method """ # Check if path is a folder or filename zip_filepath = "{0}.zip".format(filepath) if zip_filename: zip_filepath = "{0}.zip".format(zip_filename) with zipfile.ZipFile(zip_filepath, 'w') as zip_file: if os.path.isfile(filepath): zip_file.write(filepath) else: _zipdir(zip_file, filepath, filepath) class ZipFile(zipfile.ZipFile): def getChildZip(self, childZipName): """ Returns a ZipFile specified by child_zip_path that exists inside parent_zip. Arguments: parentZip (zipfile.ZipFile): parent zip childZipName (string): name of the file inside the zip """ memory_zip = cStringIO.StringIO() memory_zip.write(self.open(childZipName).read()) return ZipFile(memory_zip) def extractTo(self, childName, path): """ Extracts the specified content to the given location Arguments: parentZip (zipfile.ZipFile): parent zip childZipName (string): name of the file inside the zip path (string): file path to save extracted files to """ directory = os.path.dirname(path) source = os.path.join(directory, childName) self.extract(self.getinfo(childName), directory) shutil.move(source, path)