我正在尝试使用 tarfile 在内存中添加一个文件,然后将其写回磁盘,但我遇到的问题是,在我的最终输出中,当我提取新创建的 tar.gz 文件时,我得到一个空文件。我的代码做错了什么?
import tarfile
import io
with open('logo.png', 'rb') as f:
data = f.read()
fh = io.BytesIO()
with tarfile.open(fileobj=fh, mode='w:gz') as tar:
info = tarfile.TarInfo('some.png')
tar.addfile(info, data)
with open('/tmp/test/test.tar.gz', 'wb') as f:
f.write(fh.getvalue())
Run Code Online (Sandbox Code Playgroud)
我也尝试这样做tar.addfile(info, fh.write(data)),但这只会创建一个损坏的 tar 文件。
Ala*_*ack 12
TarFile.addfile()接受一个类似文件的对象。
当文档说:
从其中读取 tarinfo.size 字节并将其添加到存档中。
这意味着tarinfo.size用于确定要读取多少字节。因此,需要进行tarinfo.size适当的设置。
您唯一需要做的就是从源读取数据,计算长度,然后将该数据加载到 BytesIO 对象中:
例如
import tarfile
import io
with open('logo.png', 'rb') as f:
data = f.read()
source_f = io.BytesIO(initial_bytes=data)
fh = io.BytesIO()
with tarfile.open(fileobj=fh, mode='w:gz') as tar:
info = tarfile.TarInfo('logo.png')
info.size = len(data)
tar.addfile(info, source_f)
with open('test.tar.gz', 'wb') as f:
f.write(fh.getvalue())
Run Code Online (Sandbox Code Playgroud)
或者一种更有效的内存方式,寻找源文件:
f = open('logo.png', 'rb')
f.seek(0,2) # go to the end
source_len = f.tell()
f.seek(0)
fh = io.BytesIO()
with tarfile.open(fileobj=fh, mode='w:gz') as tar:
info = tarfile.TarInfo('logo.png')
info.size = source_len
tar.addfile(info, f)
with open('test.tar.gz', 'wb') as f:
f.write(fh.getvalue())
f.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7038 次 |
| 最近记录: |