gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:58:24 25 4
gpt4 key购买 nike

我想保存多个对象,例如图,在循环中直接创建到 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]: how to save a pylab figure into in-memory file which can be read into PIL image?(@unutbu's answer)显示如何在内存中保存绘图图像内容([Matplotlib]: matplotlib.pyplot.savefig),通过[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\StackOverflow\q055616877]> dir /b
code00.py

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\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\StackOverflow\q055616877]> dir /b
code00.py
export.zip

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

关于python - 保存多个对象直接从内存压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com