如何只提取 .tar.gz 成员的文件?

How do I extract only the file of a .tar.gz member?

我的目标是解压一个 .tar.gz 文件,而不是解压该文件的子目录。

我的代码基于此 question 除了解压缩 .zip 我正在解压缩 .tar.gz 文件。

我问这个问题是因为我收到的错误非常模糊,无法确定我的代码中的问题:

import os
import shutil
import tarfile

with tarfile.open('RTLog_20150425T152948.gz', 'r:gz') as tar:
    for member in tar.getmembers():
        filename = os.path.basename(member.name)
        if not filename:
            continue

        # copy file (taken from zipfile's extract)
        source = member
        target = open(os.path.join(os.getcwd(), filename), "wb")
        with source, target:
            shutil.copyfileobj(source, target)

如您所见,我从链接的问题中复制了代码并尝试将其更改为处理 .tar.gz 成员而不是 .zip 成员。在 运行 代码中出现以下错误:

Traceback (most recent call last):
  File "C:\Users\dzhao\Desktop34564444\blah.py", line 27, in <module>
    with source, target:
AttributeError: __exit__

根据我的阅读,shutil.copyfileobj 将两个 "file-like" 对象作为输入。 member 是一个 TarInfo 对象。我不确定 TarInfo 对象是否是类文件对象,所以我尝试将此行从:

更改为
source = member #to
source = open(os.path.join(os.getcwd(), member.name), 'rb')

但可以理解的是,这会引发找不到文件的错误。

我哪里不明白?

这段代码对我有用:

import os
import shutil
import tarfile

with tarfile.open(fname, "r|*") as tar:
    counter = 0

    for member in tar:
        if member.isfile():
            filename = os.path.basename(member.name)
            if filename != "myfile": # do your check
                continue

            with open("output.file", "wb") as output: 
                shutil.copyfileobj(tar.fileobj, output, member.size)

            break # got our file

        counter += 1
        if counter % 1000 == 0:
            tar.members = [] # free ram... yes we have to do this manually

但你的问题可能不是提取,而是你的文件确实不是。tar.gz而只是一个 .gz 文件。

编辑:您在 with 行上也收到错误,因为 python 正在尝试调用成员对象的 __enter__ 函数(不存在)。