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

雨燕双飞 提交于 2019-12-04 14:52:17
Simon Kirsten

This code has worked for me:

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

But your problem might not be the extraction, but rather that your file is indeed no .tar.gz but just a .gz file.

Edit: Also your getting the error on the with line because python is trying to call the __enter__ function of the member object (wich does not exist).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!