Write files from folder recursively into ZIPFile object
def zip_write_dir(zip_fileobj, dir_path, files_prefix=''):
for dirpath, dirnames, dirfiles in os.walk(dir_path):
for dirname in dirnames:
if files_prefix:
dir_prefix = '%s/%s' % (files_prefix, dirname)
else:
dir_prefix = dirname
dir_path = os.path.join(dirpath, dirname)
zip_write_dir(zip_fileobj, dir_path, files_prefix=dir_prefix)
for filename in dirfiles:
file_path = os.path.join(dirpath, filename)
zip_fileobj.write(file_path, '%s/%s' % (files_prefix, filename))
# USAGE
# -- FOLDER CONTENT
# - file1.py
# - file2.py
# - another_folder/filex.py
#
# zip_write_dir(a_zip_object, '/sample/this/', files_prefix='this')
#
# -- ZIP CONTENT
# - this/file1.py
# - this/file2.py
# - this/another_folder/filex.py