import os
import io
import zipfile
def zip_directory_into_bytes(path):
bio = io.BytesIO()
with zipfile.ZipFile(bio, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
abs_path = os.path.abspath(path)
for dir_name, sub_dirs, files in os.walk(path):
for filename in files:
abs_name = os.path.abspath(os.path.join(dir_name, filename))
file_name = abs_name[len(abs_path) + 1:]
zf.write(abs_name, file_name)
return bio.getvalue()
if __name__ == "__main__":
with open('test.zip', 'wb') as f:
f.write(zip_directory_into_bytes('.'))