如何将 tar 文件对象转为字符串
how to turn tar file object to string
我有一个包含几个文件的 tarfile 对象,其中一个名为 ffb.json
。我尝试了以下方法来提取 json 字符串,
with tarfile.open(mode="r:gz", fileobj=StringIO.StringIO(p.results)) as tar:
for tarinfo in tar:
print tarinfo.name
if tarinfo.name == './ffb.json':
print tarinfo.tobuf()
但是,print tarinfo.tobuf()
没有打印出我预期的结果:./ffb.json0000644000000000000000000000054313070524150012600 0ustar rootroot00000000000000
如果我手动提取 ffb.json,它确实包含合法的 json 字符串。
如 tarfile 的 documentation 中所述,TarInfo
仅包含文件元数据 - "It does not contain the file's data itself."
幸运的是,您可以将该 TarInfo
对象传回 TarFile.extractfile(member)
,以便将文件内容作为类文件对象获取(随后您可以 .read()
获取原始内容)。例如:print tar.extractfile(tarinfo).read()
.
或者,您可以跳过 foreach 循环并直接使用文件名调用 TarFile.extractfile(member)
(例如 print tar.extractfile("./ffb.json").read()
)。
我有一个包含几个文件的 tarfile 对象,其中一个名为 ffb.json
。我尝试了以下方法来提取 json 字符串,
with tarfile.open(mode="r:gz", fileobj=StringIO.StringIO(p.results)) as tar:
for tarinfo in tar:
print tarinfo.name
if tarinfo.name == './ffb.json':
print tarinfo.tobuf()
但是,print tarinfo.tobuf()
没有打印出我预期的结果:./ffb.json0000644000000000000000000000054313070524150012600 0ustar rootroot00000000000000
如果我手动提取 ffb.json,它确实包含合法的 json 字符串。
如 tarfile 的 documentation 中所述,TarInfo
仅包含文件元数据 - "It does not contain the file's data itself."
幸运的是,您可以将该 TarInfo
对象传回 TarFile.extractfile(member)
,以便将文件内容作为类文件对象获取(随后您可以 .read()
获取原始内容)。例如:print tar.extractfile(tarinfo).read()
.
或者,您可以跳过 foreach 循环并直接使用文件名调用 TarFile.extractfile(member)
(例如 print tar.extractfile("./ffb.json").read()
)。