从流模式tarfile中提取文件

时间:2019-04-04 14:26:39

标签: python stream tar

我有一个包含.tar文件内容的流,因此我使用tarfile.open('r |')处理它 我需要做的-是查看其中的文件列表并阅读其中的一些文件,然后将整个tar上传到另一个位置。

当我尝试在tarfile.getnames()之后使用tarfile.extractfile()时,将引发tarfile.StreamError。但是我无法提取我不知道的文件。

如何在不破坏tarfile的情况下获取文件列表?我无法将整个tar保存到RAM \ disk,因为其中的某些文件可能大于10GB。

>>> tf = tarfile.open(fileobj=open('Downloads/clean-alpine.ova', 'rb'), mode='r|')
>>> tfn = tf.getnames()
>>> tfn
['clean-alpine.ovf', 'clean-alpine.mf', 'clean-alpine-disk1.vmdk']
>>> tf.fileobj
<tarfile._Stream object at 0x7ff878dac7b8>
>>> tf.fileobj.pos
33595392
>>> ovf = tf.extractfile('clean-alpine.ovf')
>>> ovf
<ExFileObject name=''>
>>> d = ovf.read().decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/tarfile.py", line 696, in read
    self.fileobj.seek(offset + (self.position - start))
  File "/usr/lib/python3.6/tarfile.py", line 522, in seek
    raise StreamError("seeking backwards is not allowed")
tarfile.StreamError: seeking backwards is not allowed

1 个答案:

答案 0 :(得分:0)

查看TarFile.extractall()的来源很重要,就是像我在用例中一样,将TarFile用作可迭代项:

for member in tf:
    if not member.isfile():
        continue
    dest = Path.cwd() / member.name  # This is vulnerable to, like, 5 things
    with tf.extractfile(member) as tfobj:
        dest.write_bytes(tfobj.read())
相关问题