使用Python提取ZipFile,显示进度百分比?

Zac*_*own 7 python extract progress ziparchive

我知道如何使用Python提取zip存档,但我究竟如何以百分比显示该提取的进度?

Anw*_*vic 13

我建议使用tqdm,你可以pip像这样安装它:

pip install tqdm
Run Code Online (Sandbox Code Playgroud)

然后,您可以像这样直接使用它:

>>> with zipfile.ZipFile(some_source) as zf:
...     for member in tqdm(zf.infolist(), desc='Extracting '):
...         try:
...             zf.extract(member, target_path)
...         except zipfile.error as e:
...             pass
Run Code Online (Sandbox Code Playgroud)

这将产生如下结果:

Extracting : 100%|??????????| 60.0k/60.0k [14:56<00:00, 66.9File/s]
Run Code Online (Sandbox Code Playgroud)

  • @Anwarvic 如果我有 1 100MiB 文件和 99 个 KiB 文件,那么根本就不是这样的...... (3认同)

Dan*_* D. 6

extract方法没有为此提供回调,因此必须使用getinfo获取e未压缩的大小,然后打开从块中读取的文件并将其写入您希望文件前往的位置并更新百分比如果想要一个例子,还必须恢复mtime:

import zipfile
z = zipfile.ZipFile(some_source)
entry_info = z.getinfo(entry_name)
i = z.open(entry_name)
o = open(target_name, 'w')
offset = 0
while True:
    b = i.read(block_size)
    offset += len(b)
    set_percentage(float(offset)/float(entry_info.file_size) * 100.)
    if b == '':
        break
    o.write(b)
i.close()
o.close()
set_attributes_from(entry_info)
Run Code Online (Sandbox Code Playgroud)

这提取entry_nametarget_name


大多数情况也是由shutil.copyfileobj它完成的,但它也没有回复进展

ZipFile.extract方法调用的来源_extract_member使用:

source = self.open(member, pwd=pwd)
target = file(targetpath, "wb")
shutil.copyfileobj(source, target)
source.close()
target.close()
Run Code Online (Sandbox Code Playgroud)

如果成员不是ZipInfo对象,getinfo(member)则将其从名称转换为ZipInfo对象