Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python function to zip up a directory and preserve any symlinks and empty directories.
import os
import zipfile
def ZipDir(inputDir, outputZip):
'''Zip up a directory and preserve symlinks and empty directories'''
zipOut = zipfile.ZipFile(outputZip, 'w', compression=zipfile.ZIP_DEFLATED)
rootLen = len(os.path.dirname(inputDir))
def _ArchiveDirectory(parentDirectory):
contents = os.listdir(parentDirectory)
#store empty directories
if not contents:
archiveRoot = parentDirectory[rootLen:].replace('\\', '/').lstrip('/')
zipInfo = zipfile.ZipInfo(archiveRoot+'/')
zipOut.writestr(zipInfo, '')
for item in contents:
fullPath = os.path.join(parentDirectory, item)
if os.path.isdir(fullPath) and not os.path.islink(fullPath):
archiveRoot = fullPath[rootLen:].replace('\\', '/').lstrip('/')
if os.path.islink(fullPath):
zipInfo = zipfile.ZipInfo(archiveRoot)
zipInfo.create_system = 3
# long type of hex val of '0xA1ED0000L',
# say, symlink attr magic...
zipInfo.external_attr = 2716663808L
zipOut.writestr(zipInfo, os.readlink(fullPath))
zipOut.write(fullPath, archiveRoot, zipfile.ZIP_DEFLATED)
Copy link

simonwagner commented Dec 5, 2015

For an explanation of what zipInfo.external_attr actually means, look here:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment