Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python zip unzip progress bar

Tags:

python-3.x

I have a PyQt5 application that does zip/unzip operations under the hood and a general progress bar that indicates the status.
For example: if I download a file, I can track the received_bytes & total_size and calculate the current percentage.
The same can be done for the zip since it has a for loop and I can calculate the amount of processed files.

with zipfile.ZipFile(f'{path}', 'w') as z:
  for file in files:
    z.write(file_path, compress_type=zipfile.ZIP_STORED)

I would like to know is it possible for me somehow to track the progress of the unpack operation?

shutil.unpack_archive(path_from, path_to)
like image 994
IgorZ Avatar asked Jun 06 '26 18:06

IgorZ


1 Answers

Got a solution with the ZipFile

from zipfile import ZipFile

class ZipFileCustom(ZipFile):
    """ Custom ZipFile class with a callback on extractall. """

    def extractall(self, path=None, members=None, pwd=None, fn_progress=None):
        if members is None:
            members = self.namelist()

        if path is None:
            path = os.getcwd()
        else:
            path = os.fspath(path)

        for index, member in enumerate(members):
            if fn_progress:
                fn_progress(len(members), index + 1)
            self._extract_member(member, path, pwd)

As you can see I've added the fn_progress into the extractall and a bit modified its for loop.
Now can use this method together with the function to calculate percents:

def calculate_percentage(total: int, current: int):
    percent = float(current) / total
    percent = round(percent * 100)
    return percent

with ZipFileCustom('./test.zip') as zfc:
    zfc.extractall('./out', fn_progress=lambda total, current: print(f'{calculate_percentage(total, current)} %'))

The output is:

4%
8%
12%
17%
...
88%
92%
96%
100%
like image 148
IgorZ Avatar answered Jun 10 '26 19:06

IgorZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!