我想要解压缩一个文件夹,但是不想直接使用 .extractall()
,而是想要将文件解压到流中,以便我自己处理这个流。是否可以使用 tarfile
实现?或者有其他的建议吗?
你可以使用.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.
extractfile
返回一个tarfile.ExFileObject
,不能用于打开gzip.GzipFile
。是否有一种方法可以在不解压缩tar文件并打开新系统文件的情况下打开此gzip文件? - Wernergzip
模块应该可以无问题地接受该对象,但Python 2版本仍然尝试在文件对象上寻找。要么升级到Python 3,要么先将文件复制到磁盘上,或者在读取时解码流,参见Python逐块解压缩gzip。 - Martijn Pieters在使用网络流传输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
tarfile
库吗? - Chris Medrela