Python tarfile progress output?

Viewed 11042

I'm using the following code to extract a tar file:

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

However, I'd like to keep tabs on the progress in the form of which files are being extracted at the moment. How can I do this?

EXTRA BONUS POINTS: is it possible to create a percentage of the extraction process as well? I'd like to use that for tkinter to update a progress bar. Thanks!

7 Answers

You can just use tqdm() and print the progress of the number of files being extracted:

import tarfile
from tqdm import tqdm

# open your tar.gz file
with tarfile.open(name=path) as tar:

    # Go over each member
    for member in tqdm(iterable=tar.getmembers(), total=len(tar.getmembers())):

        # Extract member
        tar.extract(member=member)

This is what I use, without monkey patching or needing the number of entries.

def iter_tar_files(f):
    total_bytes = os.stat(f).st_size
    with open(f, "rb") as file_obj,\
        tarfile.open(fileobj=file_obj, mode="r:gz") as tar:
        for member in tar.getmembers():
            f = tar.extractfile(member)
            if f is not None:
                content = f.read()
                yield member.path, content
            # This prints something like: 512/1024 = 50.00%
            print(f"{file_obj.tell()} / {total_bytes} = {file_obj.tell()/total_bytes*100:.2f}%")
Related