如何解决使用python将tar文件写入缓冲区
我想获取我创建的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())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。