Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a zip file in stream without directory structure

I’m working on a Flask app to return a zip file to a user of a directory (a bunch of photos) but I don’t want to include my server directory structure in the returned zip. Currently, I have this :

def return_zip():
    dir_to_send = '/dir/to/the/files'
    base_path = pathlib.Path(dir_to_send)
    data = io.BytesIO()
    with zipfile.ZipFile(data, mode='w') as z:
        for f_name in base_path.iterdir():
            z.write(f_name)
    data.seek(0)
    return send_file(data, mimetype='application/zip', as_attachment=True, attachment_filename='data.zip')

This works great for creating and returning the zip but the file includes the structure of my server i.e.

/dir/to/the/files/image.jpg, image1.jpg etc...

In the zip I just want the files, not their associated directory. How could I go about this?
Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use the arcname parameter to rename the file in the zip file. We can remove the directory structure by simply passing the write function the name of the file you want to add, this can be accomplished as follows:

def return_zip():
    dir_to_send = '/dir/to/the/files'
    base_path = pathlib.Path(dir_to_send)
    data = io.BytesIO()
    with zipfile.ZipFile(data, mode='w') as z:
        for f_name in base_path.iterdir():
            z.write(f_name, arcname=f_name.name)
    data.seek(0)
    return send_file(data, mimetype='application/zip', as_attachment=True, attachment_filename='data.zip')

You can read more about the details of zipfile write function here: https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.write

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading