Skip to content

Instantly share code, notes, and snippets.

@baradhiren
Created May 17, 2021 04:59
Show Gist options
  • Save baradhiren/0c2f8763ea89219a4850989600702e66 to your computer and use it in GitHub Desktop.
Save baradhiren/0c2f8763ea89219a4850989600702e66 to your computer and use it in GitHub Desktop.
Extract directory from a zip file Python
def extractDirectory(zipName, directoryName, destFilePath):
try:
with zipfile.ZipFile(zipName) as z:
for file in z.namelist():
if file.startswith(directoryName) and file != directoryName + '/':
path = os.path.join(destFilePath, 'Any/subsequent/dirs')
dirtemp = '/'.join(path.split('/')[0:-1])
Path(dirtemp).mkdir(parents=True, exist_ok=True)
with z.open(file) as zf, open(path, 'wb') as f:
shutil.copyfileobj(zf, f)
except Exception as e:
print('[ERROR] Could not extract {}.'.format(directoryName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment