小编Joh*_*ald的帖子

在 python 中将 BytesIO 添加到 BytesIO tar.gz

我在从 BytesIO 对象用 Python 编写 .tar.gz 文件时遇到问题。只编写普通的 tar 文件效果很好,但如果我将写入模式更改为 .tar.gz (或 bz 或 xz),它不会生成有效的 tar 文件。

我做了一个精简版本如下:

def string_to_tarfile(name, string):
    encoded = string.encode('utf-8')
    s = BytesIO(encoded)

    tar_info = tarfile.TarInfo(name=name)
    tar_info.mtime=time.time()
    tar_info.size=len(encoded)

    return s, tar_info

file1='hello'
file2='world'

f=BytesIO()
tar = tarfile.open(fileobj=f, mode='w:gz')
string, tar_info = string_to_tarfile("file1.txt", file1)
tar.addfile(tarinfo=tar_info, fileobj=string)

string, tar_info = string_to_tarfile("file2.txt", file2)
tar.addfile(tarinfo=tar_info, fileobj=string)

f.seek(0)
with open('whatevs.tar.gz', 'wb') as out:
    out.write(f.read())
Run Code Online (Sandbox Code Playgroud)

这应该做的是创建一个包含“file1.txt”和“file2.txt”的whatevs.tar.gz 文件。

如果我将 'w:gz' 替换为 'w'(并删除 .gz 结尾),我会得到一个包含正确内容的 tarfile,但将其添加回来会导致 10 字节损坏的 tar.gz 文件

我想将其写入 bytesio,因为我实际上正在将其上传到 S3。

我不确定我是否严重误读了这里的文档,我已经浏览了一百万篇文章,他们要么制作 tar …

python tar bytesio

4
推荐指数
1
解决办法
3627
查看次数

标签 统计

bytesio ×1

python ×1

tar ×1