我知道如何使用Python提取zip存档,但我究竟如何以百分比显示该提取的进度?
答案 0 :(得分:6)
提取方法没有为此提供回调,因此必须使用getinfo
来获取未压缩的大小,然后打开从块中读取的文件并将其写入您想要的位置如果想要一个例子,那么要更新mtime的文件还需要恢复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)
这会将entry_name
提取到target_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()
如果成员不是ZipInfo对象,则getinfo(member)
将成员从名称转换为ZipInfo对象
答案 1 :(得分:0)
我建议使用tqdm
,它非常简单,就像这样:
>>> 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
这将产生类似这样的结果:
Extracting : 100%|██████████| 60.0k/60.0k [14:56<00:00, 66.9File/s]
答案 2 :(得分:0)
抱歉看到这个有点晚了。有一个类似的问题,需要一个等价于 zipfile.Zipfile.extractall
。如果您有 tqdm>=4.40.0
(我一年多前发布的),那么:
from os import fspath
from pathlib import Path
from shutil import copyfileobj
from zipfile import ZipFile
from tqdm.auto import tqdm # could use from tqdm.gui import tqdm
from tqdm.utils import CallbackIOWrapper
def extractall(fzip, dest, desc="Extracting"):
"""zipfile.Zipfile(fzip).extractall(dest) with progress"""
dest = Path(dest).expanduser()
with ZipFile(fzip) as zipf, tqdm(
desc=desc, unit="B", unit_scale=True, unit_divisor=1024,
total=sum(getattr(i, "file_size", 0) for i in zipf.infolist()),
) as pbar:
for i in zipf.infolist():
if not getattr(i, "file_size", 0): # directory
zipf.extract(i, fspath(dest))
else:
with zipf.open(i) as fi, open(fspath(dest / i.filename), "wb") as fo:
copyfileobj(CallbackIOWrapper(pbar.update, fi), fo)