Adding a file-like object to a zip file in Python

The Python ZipFile API apparently allows you to pass a file path ZipFile.writeor a byte string in ZipFile.writestr, but there is nothing between them. I would like to be able to transfer the file as an object, in this case a django.core.files.storage.DefaultStorage, but any file-like object in principle. At the moment, I think that I will either have to save the file to disk or read it in memory. None of them are perfect.

+5
source share
1 answer

You are right, these are only two options. If your object is DefaultStoragelarge, you can first save it to disk; otherwise I would use:

zipped = ZipFile(...)
zipped.writestr('archive_name', default_storage_object.read())

default_storage_object StringIO, default_storage_object.getvalue().

+6

All Articles