使用python将tar文件写入缓冲区

问题描述

我想获取我创建的tar.gz的数据

在这个例子中,我创建了 tar.gz 文件,然后读取内容

import tarfile
with tarfile.open('/tmp/test.tar.gz','w:gz') as f:
    f.add("/home/chris/.zshrc")

with open ('/tmp/test.tar.gz','rb') as f:
    data = f.read()

我有什么简短而干净的方法吗?我不需要 tar.gz 文件,只需要数据

解决方法

通过指定 tarfile 作为 fileobj 实例的 io.BytesIO 参数来使用内存缓冲区:

import tarfile
from io import BytesIO


buf = BytesIO()    
with tarfile.open('/tmp/test.tar.gz','w:gz',fileobj=buf) as f:
    f.add("/home/chris/.zshrc")

data = buf.getvalue()
print(len(data))

或者你可以这样做:

import tarfile
from io import BytesIO


buf = BytesIO() 
with tarfile.open('/tmp/test.tar.gz',fileobj=buf) as f:
    f.add("/home/chris/.zshrc")
   
buf.seek(0,0) # reset pointer back to the start of the buffer
with tarfile.open('/tmp/test.tar.gz','r:gz',fileobj=buf) as f:
    print(f.getmembers())