在Python中直接从内存中保存多个对象

问题描述 投票:2回答:1

我想保存多个对象,例如数字,直接创建一个循环到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)

如果是肯定答案,有没有办法对任何类型的对象做同样的事情,还是依赖于对象类型?

非常感谢

python matplotlib zip zipfile
1个回答
0
投票
  1. @BoarGules指出[Python 3]: ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, compresslevel=None)允许使用内存中的内容创建一个zip文件成员
  2. qazxsw poi演示了如何通过q​​azxsw poi将情节图像内容保存在记忆中(qazxsw poi)
  3. 所有你需要做的就是结合以上2

code.朋友:

[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 3]: class io.BytesIO([initial_bytes])传递给ZipFile的初始化程序。

© www.soinside.com 2019 - 2024. All rights reserved.