'Python - load an in-memory ZipFile object as bytes

I have a script which creates a closed in-memory ZipFile object that I need to post as a bytestring (using requests); how do I do that? I have tried opening the file, which fails with "TypeError: expected str, bytes or os.PathLike object, not ZipFile"

The script works just fine if I write the ZipFile to a file and then open that file for the post data. However it will probably iterate over a couple million files, and that seems like a lot of temp files, and disk activity.

import io
import zipfile
from PIL import Image

z = io.BytesIO()
zfile = zipfile.ZipFile(z,"a")

zipdict = {}

img_loc = "D:/Images/seasons-3.jpg"
im_original = Image.open(img_loc)
imfmt = im_original.format
im = im_original.copy()
im_original.close()
im_out = io.BytesIO()
im.save(im_out,imfmt)
zfile.writestr("seasons-3.jpg",im_out.getvalue())
im_out.close()
zipdict['seasons-3']=zfile
zfile.close()

running with error:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
>>> zipdict['seasons-3']
<zipfile.ZipFile [closed]>
>>> pl_data = open(zipdict['seasons-3'])
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    pl_data = open(zipdict['seasons-3'])
TypeError: expected str, bytes or os.PathLike object, not ZipFile
>>> 


Solution 1:[1]

zfile is closed. It's useless to you. The thing you need to use now is z, the file-like object that was managing the underlying binary storage for the ZipFile.

You can use z.getvalue() to get a bytestring representing the contents of z, just like you did with im_out, or you can seek back to the beginning with z.seek(0) and use it with the parts of requests that take file-like objects.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2357112