python tar文件如何将文件提取到流中

Rob*_* W. 8 python stream tar

我试图提取一个压缩文件夹,但不是直接使用.extractall(),我想将文件解压缩为流,以便我可以自己处理流.是否可以使用它tarfile?或者有什么建议吗?

Mar*_*ers 17

您可以file使用该.extractfile()方法从tar文件中获取每个文件作为python 对象.遍历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.
Run Code Online (Sandbox Code Playgroud)

  • 如果fileobj是gzip文件,是否可以解压它? (2认同)
  • 是的,但是在 tarfile 中我有一个 gzip 文件(不幸的是有人用我的 gzip 文件创建了一个压缩的 tarfile...)。`extractfile` 返回一个 `tarfile.ExFileObject` 不能用于打开 gzip.GzipFile。有没有办法在不解压tar文件的情况下打开这个gzip文件并打开新的系统文件? (2认同)