簡體   English   中英

如何僅提取.tar.gz成員的文件?

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

我的目標是解壓縮.tar.gz文件,而不是導致文件的子目錄。

我的代碼是基於這個問題,除了解壓縮.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\Desktop\123456\444444\blah.py", line 27, in <module>
    with source, target:
AttributeError: __exit__

從我已經完成的閱讀中, shutil.copyfileobj將兩個“類文件”對象作為輸入。 memberTarInfo對象。 我不確定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__函數(不存在)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM