Skip to content

Instantly share code, notes, and snippets.

@SuoXC
Created December 6, 2019 04:16
Show Gist options
  • Save SuoXC/bb168aa0e7dcebdc7517b34e4be807d2 to your computer and use it in GitHub Desktop.
Save SuoXC/bb168aa0e7dcebdc7517b34e4be807d2 to your computer and use it in GitHub Desktop.
use zipfile to unzip a zipfile recursively to target directory
import os
import zipfile
def recursive_unzip(zip_file, target_dir):
print("export: ", zip_file)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
with zipfile.ZipFile(zip_file, 'r') as zf:
name_list = zf.namelist()
for path_name in name_list:
if zf.getinfo(path_name).is_dir():
os.makedirs(os.path.join(target_dir, path_name), exist_ok=True)
elif zipfile.is_zipfile(zf.open(path_name, 'r')):
# print('unzip %s to %s' % (path_name, os.path.join(target_dir, path_name)))
recursive_unzip(zip_file=zf.open(path_name, 'r'), target_dir=os.path.join(target_dir, path_name))
else:
# print('unzip %s to %s' % (path_name, os.path.join(target_dir, path_name)))
# print('unzip', path_name, os.path.join(target_dir, os.path.dirname(path_name)))
zf.extract(path_name, target_dir)
if __name__ == '__main__':
zip_file = r''
target_dir = r''
recursive_unzip(zip_file=zip_file, target_dir=target_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment