【发布时间】: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