I
I
Ilya2016-03-22 14:45:31
Python
Ilya, 2016-03-22 14:45:31

How to zip a folder of files using BitesIO in Python?

Tell me how to pack a folder or only files from it using BitesIO and give it to the user.
I do all this in Django.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2016-03-22
@nuBacuk

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('.'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question