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

Joh*_*ald 4 python tar bytesio

我在从 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 文件(效果很好,但我不想),要么写入本地文件系统(再次) ,我上传到S3,我不想写在本地)。

谢谢你!

小智 5

我认为关闭 tarfile 对象可以解决您的问题。

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)
tar.close() # <-- 
Run Code Online (Sandbox Code Playgroud)

为了避免遇到此类打开文件问题,我认为将其与with如下语句一起使用会更安全:

f = BytesIO()
with tarfile.open(fileobj=f, mode='w:gz') as tar:
    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)
Run Code Online (Sandbox Code Playgroud)