Skip to content
Advertisement

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!

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement