Skip to content

Instantly share code, notes, and snippets.

@nmaier
Created January 19, 2011 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmaier/787095 to your computer and use it in GitHub Desktop.
Save nmaier/787095 to your computer and use it in GitHub Desktop.
import os, sys
from zipfile import ZipFile, ZIP_DEFLATED
def stripdirectoryentries(source, target):
szf = ZipFile(source)
try:
if os.path.exists(target):
raise Exception("Target %s already exists" % target)
tzf = ZipFile(target, "w", ZIP_DEFLATED)
try:
try:
for entry in szf.namelist():
if entry[-1] in (os.path.sep, os.path.altsep):
# omit directory entries
continue
tzf.writestr(entry, szf.read(entry), ZIP_DEFLATED)
finally:
tzf.close()
except Exception,ex:
# Remove broken target
try: os.unlink(target)
except: pass
raise ex
finally:
szf.close()
if __name__ == '__main__':
try:
try:
s,t = sys.argv[1:]
except:
raise Exception("Usage: strip-zip.py source-zip target-zip")
stripdirectoryentries(s,t)
sys.exit(0)
except Exception,ex:
print >>sys.stderr, ex
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment