如何使用python将以下代码中生成的所有图像保存到Zip文件中?

2024-03-29 06:45:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要解码内容数组列表中的数据并生成一个图像,下面的代码就是这样做的

    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

如何将生成的所有图像直接存储到一个zip文件中,该文件包含通过解码上述列表[content\u arrays]中的base64字符串生成的所有图像

下载数据的当前文件结构:

 -- Desktop 
     -- image1.png
     -- image2.png

下载数据所需的文件结构:

 -- Desktop
     -- Data.zip 
        -- image1.png
        -- image2.png

我用过python zipfile模块,但搞不懂什么。 如果有任何可能的方法,请给出你的建议


Tags: 文件数据图像列表imgdatapngcontent
2条回答

在您的例子中,您可以遍历文件名列表

with ZipFile('images.zip', 'w') as zip_obj:
   # Add multiple files to the zip
   for filename in filenames:
       zip_obj.write(filename)

您只需使用zipfile模块,然后将内容写入zip中的不同文件。在本例中,我只是将内容写入内容列表中每个项目的zip中的一个文件。我在这里也使用writestr方法,所以我不需要在磁盘上有物理文件,我只需要在内存中创建我的内容并将其写入我的zip,而不是首先在操作系统上创建一个文件,然后在zip中写入该文件

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)

输出enter image description here

enter image description here

相关问题 更多 >