【问题标题】:saving string to tarfile in python 3 throws unexpected end of data error在 python 3 中将字符串保存到 tarfile 会引发意外的数据结束错误
【发布时间】:2018-03-02 17:47:15
【问题描述】:

我正在尝试打开一个包含 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。 (顺便说一句,我已经验证了我要编写的所有字符串的长度都是非零的,并且还验证了在文件对象上调用 tell() 与在字符串上调用 len() 返回的值相同。)

我找到了this prior SO,这表明问题在于StringIO 未编码,因此我将BytesIO 换成了StringIO,然后换成了fobj.write(cleaned.encode("utf-8")),但这仍然会引发相同的错误。

我还尝试过简单地不设置 TarInfo 对象的大小,然后该代码运行,但创建了一个包含一堆空文件的存档。

我错过了什么?谢谢!

【问题讨论】:

    标签: python string python-3.x gzip tar


    【解决方案1】:

    .addfile() 方法可能只是在您提供给它的文件对象上调用.read() - 在这种情况下它不会返回任何内容,因为您已经在文件的末尾。尝试在该行之前添加fobj.seek(0)

    【讨论】:

    • 天啊。 手掌到额头 我认真地花了一个小时尝试调试它,它实际上就是这么简单。谢谢,朋友。
    • 节省时间!现在与 xml.dom.minidom.parse(file) 有类似的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2013-07-23
    • 2012-01-22
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    相关资源
    最近更新 更多