Skip to content

Instantly share code, notes, and snippets.

@CocoaRush
Last active December 14, 2021 18:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CocoaRush/6266085 to your computer and use it in GitHub Desktop.
Save CocoaRush/6266085 to your computer and use it in GitHub Desktop.
unzip a zip file using Python. The zip may created in Win OS and would have a lot of gibberish in file name when unzipped in MAC OS, this simple snippet aim to solved the above problem stated.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def unzip(zfile, md=False):
basedir = ''
if md:
basedir = prepareBaseDir(zfile)
zfile = zipfile.ZipFile(zfile, 'r')
for name in zfile.namelist():
uname = name.decode('gbk')
if uname.endswith('.DS_Store'):
continue
#prepare directory
dirs = os.path.dirname(uname)
if basedir:
dirs = os.path.join(basedir, dirs)
print 'extracting: ' + uname
if dirs and not os.path.exists(dirs):
print 'prepare directories: ', dirs
os.makedirs(dirs)
#ready to unzip file
data = zfile.read(name)
if basedir:
uname = os.path.join(basedir, uname)
if not os.path.exists(uname):
fo = open(uname, 'w')
fo.write(data)
fo.close()
zfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment