从streammode tarfi提取文件

2024-04-27 03:32:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含.tar文件内容的流,所以我使用tarfile.open文件('r |') 我需要做的是查看其中的文件列表并读取其中的一些文件,然后将整个tar上传到另一个地方。你知道吗

当我试着tarfile.extractfile文件()之后tarfile.getnames文件名()它提出了一个tarfile.StreamError文件. 但我不能提取文件的名称,我不知道。你知道吗

我怎样才能得到文件列表而不破坏文件?我无法将整个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

Tags: 文件inclean列表tflinetaropen
1条回答
网友
1楼 · 发布于 2024-04-27 03:32:34

查看^{}的源代码,重要的一点是使用TarFile作为iterable,就像我在用例中所做的那样:

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())

相关问题 更多 >