我有一个脚本,它创建一个封闭的内存中 ZipFile 对象,我需要将其作为字节字符串发布(使用请求);我怎么做?我尝试打开文件,但失败并显示“TypeError:预期的 str、字节或 os.PathLike 对象,而不是 ZipFile”
如果我将 ZipFile 写入文件然后打开该文件以获取发布数据,该脚本就可以正常工作。但是,它可能会迭代数百万个文件,这似乎是很多临时文件和磁盘活动。
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()
运行错误:
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
>>>