保存多个对象直接从内存压缩

save multiple objects to zip directly from memory

我想保存多个对象,例如图,在循环中直接创建到 zip 文件,而不将它们保存在目录中。

目前我正在将图形保存在一个文件夹中,然后压缩它们。

    import matplotlib.pyplot as plt
    from zipfile import ZipFile
    
    for i in range(10):
        plt.plot([i, i])
        plt.savefig('fig_' + str(i) + '.png')
        plt.close()

    image_list = []
    for file in os.listdir(save_path):
        if file.endswith(".png"):
            image_list.append(os.path.join(save_path, file))

    with ZipFile(os.path.join(save_path, 'export.zip'), 'w') as zip:
        for file in image_list:
            zip.write(file)

如果是肯定的答案,有没有办法对任何类型的对象做同样的事情,或者它是否取决于对象类型?

  1. @BoarGules 指出 [Python.Docs]: ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, compresslevel=None) 允许创建 一个 zip 文件成员,其内容来自内存

  2. [SO]: 如何将pylab图形保存到可以读入PIL图像的内存文件中? (@unutbu 的回答) 显示如何在内存中保存绘图图像内容[Matplotlib]: matplotlib.pyplot.savefig), via [Python.Docs]: class io.BytesIO([initial_bytes])

  3. 你所要做的就是结合以上 2

code00.py:

#!/usr/bin/env python

import sys
import matplotlib.pyplot as plt
import zipfile
import io


def main(*argv):
    zip_file_name = "export.zip"
    print("Creating archive: {:s}".format(zip_file_name))
    with zipfile.ZipFile(zip_file_name, mode="w") as zf:
        for i in range(3):
            plt.plot([i, i])
            buf = io.BytesIO()
            plt.savefig(buf)
            plt.close()
            img_name = "fig_{:02d}.png".format(i)
            print("  Writing image {:s} in the archive".format(img_name))
            zf.writestr(img_name, buf.getvalue())


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

输出:

[cfati@CFATI-5510-0:e:\Work\Dev\Whosebug\q055616877]> dir /b
code00.py

[cfati@CFATI-5510-0:e:\Work\Dev\Whosebug\q055616877]> "e:\Work\Dev\VEnvs\py_pc064_03.08.07_test0\Scripts\python.exe" code00.py
Python 3.8.7 (tags/v3.8.7:6503f05, Dec 21 2020, 17:59:51) [MSC v.1928 64 bit (AMD64)] 64bit on win32

Creating archive: export.zip
  Writing image fig_00.png in the archive
  Writing image fig_01.png in the archive
  Writing image fig_02.png in the archive

Done.

[cfati@CFATI-5510-0:e:\Work\Dev\Whosebug\q055616877]> dir /b
code00.py
export.zip

您会注意到,(图像)文件根本没有压缩(存档大小略大于成员大小的总和)。要启用压缩,还要将 compression=zipfile.ZIP_DEFLATED 传递给 ZipFile 的初始化程序。