Python: Create a ZIP file and add files to it

With the following code, we can easily create a ZIP file in Python, and then add objects to it.

from zipfile import ZipFile

# Here, I am defining the zip file and path from a project called u.name
# The 'w' means 'write'
# Don't forget the .zip in the file name
zipName = u.name + "_" + datetime.today().strftime("%Y%m%d%H%M") + ".zip"
zipPath = settings.MEDIA_ROOT / u.name
zipObj = ZipFile(zipPath / zipName,'w')

# We can then add a file to our ZIP. This file already exists elsewhere, under the savepath variable. 
# filename is the name of this file as saved within the ZIP file
zipObj.write(savepath, filename)

#finally, remember to close the ZIP file once done
zipObj.close()