【发布时间】:2012-11-13 18:19:57
【问题描述】:
我正在尝试提取压缩文件夹,但不是直接使用.extractall(),而是想将文件提取到流中,以便我自己处理流。是否可以使用tarfile 来做到这一点?或者有什么建议吗?
【问题讨论】:
-
你的意思是
tarfile库吗? -
是的,抱歉打错了
我正在尝试提取压缩文件夹,但不是直接使用.extractall(),而是想将文件提取到流中,以便我自己处理流。是否可以使用tarfile 来做到这一点?或者有什么建议吗?
【问题讨论】:
tarfile库吗?
在网络流式传输 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
【讨论】:
您可以使用 .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.
【讨论】:
tarfile 模块会为您处理压缩。见tarfile.open() documentation,默认模式为r,透明检测压缩并根据需要处理解压。
extractfile 返回一个 tarfile.ExFileObject,它不能用于打开 gzip.GzipFile。有没有办法在不解压tarfile的情况下打开这个gzip文件并打开新的系统文件?
gzip 模块应该毫无问题地获取该对象,但 Python 2 版本仍然尝试在文件对象上查找。要么升级到 Python 3,要么先将文件复制到磁盘,或者在读取流时对其进行解码,请参阅Python decompressing gzip chunk-by-chunk