【问题标题】:How to dump in memorry files to an in memmory tar and than dump that tar to disk in python如何将内存文件转储到内存中的 tar,然后在 python 中将该 tar 转储到磁盘
【发布时间】:2022-01-23 07:22:40
【问题描述】:

我的 python 内存中有很多图像,我想将它们放在 内存中 tar 中,之后我想将该 tar 刷新到磁盘。

我想在内存中执行此操作,以防止将大量小文件写入我的磁盘。

到目前为止,我有一种将图像保存为内存文件的方法

import imageio

im = np.zeros((256,256))
out_file =  io.BytesIO()
imageio.imsave(out_file, im, format = 'jpg')

我也可以将这些内存文件放入内存tar中。

import tarfile

t = tarfile.TarInfo("helloworld.tif")
t.size = len(out_file.getbuffer())
tarBuffer = io.BytesIO()
tar =  tarfile.TarFile(mode="w", fileobj=tarBuffer)
tar.addfile(t, io.BytesIO(out_file.getbuffer()))

但现在我不知道如何将内存中的 tar 文件转入我的磁盘。

有没有人对如何做到这一点有任何建议?

【问题讨论】:

  • 好像你会在this 帖子中这样说;只需打开文件句柄f 指向您要写入磁盘的最终tarfile 的路径,然后在seek 开始之后执行f.write(tarBuffer.getvalue()) 之类的操作。

标签: python tar bytesio


【解决方案1】:

好吧,经过一番折腾,我终于找到了工作。

import numpy as np
import io
import tarfile
import imageio
import time

#create dummy image
im = np.zeros((256,256))

#create memory file
out_file =  io.BytesIO()
imageio.imsave(out_file, im, format = 'jpg')

#create memory tar
tarBuffer = io.BytesIO()

#write memory file to memory tar
t = tarfile.TarInfo("helloworld.tif")
t.size = len(out_file.getbuffer())
with tarfile.open("foo.tar", mode="w:gz", fileobj= tarBuffer) as tar:
    tar.addfile(t, io.BytesIO(out_file.getbuffer()))

#write memory tar to disk
tarBuffer.seek(0, 0)
with open('out.tar', 'wb') as dump:
    dump.write(tarBuffer.read()) 

#close the files
out_file.close()
tarBuffer.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2014-06-10
    • 2015-05-21
    • 2021-07-08
    • 2018-08-03
    相关资源
    最近更新 更多