【问题标题】:python tar file how to extract file into streampython tar文件如何将文件提取到流中
【发布时间】:2012-11-13 18:19:57
【问题描述】:

我正在尝试提取压缩文件夹,但不是直接使用.extractall(),而是想将文件提取到流中,以便我自己处理流。是否可以使用tarfile 来做到这一点?或者有什么建议吗?

【问题讨论】:

  • 你的意思是tarfile库吗?
  • 是的,抱歉打错了

标签: python stream tar


【解决方案1】:

在网络流式传输 tar 文件时,我无法extractfile,而是这样做了:

from backports.lzma import LZMAFile
import tarfile
some_streamed_tar = LZMAFile(requests.get('http://some.com/some.tar.xz').content)
with tarfile.open(fileobj=some_streamed_tar) as tf:
    tarfileobj.extractall(path="/tmp", members=None)

并阅读它们:

for fn in os.listdir("/tmp"):
    with open(os.path.join(t, fn)) as f:
        print(f.read())

python 2.7.13

【讨论】:

【解决方案2】:

您可以使用 .extractfile() 方法从 tar 文件中获取每个文件作为 python file 对象。循环 tarfile.TarFile() 实例以列出所有条目:

import tarfile

with tarfile.open(path) as tf:
    for entry in tf:  # list each entry one by one
        fileobj = tf.extractfile(entry)
        # fileobj is now an open file object. Use `.read()` to get the data.
        # alternatively, loop over `fileobj` to read it line by line.

【讨论】:

  • 如果fileobj是gzip文件,是否可以解压?
  • @Werner:tarfile 模块会为您处理压缩。见tarfile.open() documentation,默认模式为r,透明检测压缩并根据需要处理解压。
  • 是的,但是在 tar 文件中我有一个 gzip 文件(不幸的是,有人用我的 gzip 文件创建了一个压缩的 tar 文件……)。 extractfile 返回一个 tarfile.ExFileObject,它不能用于打开 gzip.GzipFile。有没有办法在不解压tarfile的情况下打开这个gzip文件并打开新的系统文件?
  • @Werner:我认为您使用的是 Python 2? Python 3 的 gzip 模块应该毫无问题地获取该对象,但 Python 2 版本仍然尝试在文件对象上查找。要么升级到 Python 3,要么先将文件复制到磁盘,或者在读取流时对其进行解码,请参阅Python decompressing gzip chunk-by-chunk
  • 是的,不幸的是,仍然在 python 2 上,并且由于它是环境的一部分,因此无法升级。好的,非常感谢!找不到这方面的任何信息……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多