[英]How can I save all the generated images from the following code to a Zip file using python?
I need to decode the data in the content_arrays list and generate an image , The following code does that 我需要解码content_arrays列表中的数据并生成一个图像,以下代码可以做到这一点
content_arrays = ['ljfdslkfjaslkfjsdlf' , 'sdfasfsdfsdfsafs'] // Contains a list of base64 encoded data
i=0
for content in content_arrays:
img_data = (content_arrays[i])
with open(filename, "wb") as fh:
fh.write(base64.b64decode(img_data))
i=i+1
How can I store all the generated images directly to a single zip file which contains all the images that are generated by decoding the base64 string from the above list[content_arrays]. 如何将所有生成的图像直接存储到单个zip文件中,该文件包含通过解码上述列表[content_arrays]中的base64字符串生成的所有图像。
Current File Structure of the downloaded data :: 下载数据的当前文件结构::
-- Desktop
-- image1.png
-- image2.png
Required File Structure of the downloaded data :: 下载数据的必需文件结构::
-- Desktop
-- Data.zip
-- image1.png
-- image2.png
I've used python zipfile module , but couldn't figure out things. 我使用了python zipfile模块,但无法弄清楚。 If there is any possible way , please do give your suggestions ..
如果有任何可能的方法,请提出您的建议。
In your case, you can iterate over the list of filenames 就您而言,您可以遍历文件名列表
with ZipFile('images.zip', 'w') as zip_obj:
# Add multiple files to the zip
for filename in filenames:
zip_obj.write(filename)
you can just use the zipfile module and then write the content to separate files in the zip. 您可以只使用zipfile模块,然后将内容写入zip中的单独文件。 In this example i am just writing the content to a file inside the zip for each item in contents list.
在此示例中,我只是将内容写入目录列表中每个项目的zip文件中。 I am also using the writestr method here so i dont have to have physical files on the disk i can just create my content in memory and write it in my zip rather then having to first create it as a file on the OS and then write the file in the zip
我也在这里使用writestr方法,因此我不必在磁盘上拥有物理文件,我只需在内存中创建内容并将其写入zip中即可,而不必先在OS上将其创建为文件,然后将其写入压缩文件
from zipfile import ZipFile
with ZipFile("data.zip", "w") as my_zip:
content_arrays = ['ljfdslkfjaslkfjsdlf', 'sdfasfsdfsdfsafs']
for index, content in enumerate(content_arrays):
#do what ever you need to do here with your content
my_zip.writestr(f'file_{index}.txt', content)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.