将字符串保存到 python 中的 tarfile 3 引发意外的数据结束错误

saving string to tarfile in python 3 throws unexpected end of data error

我正在尝试打开一个充满 json 数据的 tar.gz 文件,从中提取文本,然后将它们保存回 tar.gz。到目前为止,这是我在 Python 3 中的代码。

from get_clean_text import get_cleaned_text # my own module
import tarfile
import os
import json
from io import StringIO
from pathlib import Path


def make_clean_gzip(inzip):
    outzip = "extracted/clean-" + inzip
    with tarfile.open(inzip, 'r:gz') as infile, tarfile.open(outzip, 'w:gz') as outfile:
        jfiles = infile.getnames()
        for j in jfiles:
            dirtycase = json.loads(infile.extractfile(j).read().decode("utf-8"))
            cleaned = get_cleaned_text(dirtycase)
            newtarfile = tarfile.TarInfo(Path(j).stem + ".txt")
            fobj = StringIO()
            fobj.write(cleaned)
            newtarfile.size = fobj.tell()
            outfile.addfile(newtarfile, fobj)

但是,这会引发 OSError: unexpected end of data。 (顺便说一下,我已经验证了我想写的所有字符串的长度都是非零的,并且还验证了在文件对象 returns 上调用 tell() 与调用 [=14 的值相同=] 在字符串上。)

我发现 this prior SO,这表明问题是 StringIO 未编码,所以我将 BytesIO 换成 StringIO,然后 fobj.write(cleaned.encode("utf-8")),但这仍然会引发相同的错误。

我也试过简单地不设置 TarInfo 对象的大小和代码 运行,而是创建了一个包含一堆空文件的存档。

我错过了什么?谢谢!

.addfile() 方法大概只是调用 .read() 你给它的文件对象 - returns 在这种情况下什么都没有,因为你 已经在文件结尾。尝试在该行之前添加 fobj.seek(0)