我有一个脚本,它创建了一个封闭的内存中的ZipFile对象,我需要将其作为一个字节字符串发送(使用请求);我该怎么做呢?我曾尝试打开该文件,但失败并显示"TypeError: expected str,bytes or os.PathLike object,not ZipFile“。
如果我将ZipFile写到一个文件中,然后打开该文件作为post数据,那么这个脚本就能正常工作。然而,它可能会迭代超过两百万个文件,这似乎是许多临时文件和磁盘活动。
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
>>> 发布于 2018-11-21 16:57:50
zfile已关闭。这对你没用。现在需要使用的是z,它是一个类似文件的对象,用于管理ZipFile的底层二进制存储。
您可以使用z.getvalue()来获取表示z内容的字节字符串,就像您使用im_out所做的那样,或者您可以使用z.seek(0)返回到开头,并将其用于requests中接受类似文件的对象的部分。
https://stackoverflow.com/questions/53397725
复制相似问题