使用Python提取ZipFile,显示进度百分比?
我知道如何使用 Python 提取 zip 存档,但如何以百分比形式显示提取进度?
I know how to extract a zip archive using Python, but how exactly do I display the progress of that extraction in a percentage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我建议使用 tqdm,您可以使用 pip 安装它,如下所示:
然后,您可以直接使用它,如下所示:
这将产生如下所示的内容:
I suggest using
tqdm
, you can install it usingpip
like so:Then, you can use it directly like so:
This will produce something like so:
extract 方法不提供对此的回调,因此必须使用 getinfo 来获取 e 未压缩的大小,然后打开从块中读取的文件并将其写入您想要的位置要更新百分比的文件还必须恢复 mtime(如果需要)示例:
这会将
entry_name
提取到target_name
大部分也是由 < code>shutil.copyfileobj 但它没有回调进度,或者
ZipFile.extract
方法调用的源_extract_member
使用:where member has如果它不是 ZipInfo 对象,则通过
getinfo(member)
将名称从名称转换为 ZipInfo 对象the extract method doesn't provide a call back for this so one would have to use
getinfo
to get the e uncompressed size and then open the file read from it in blocks and write it to the place you want the file to go and update the percentage one would also have to restore the mtime if that is wanted an example:this extracts
entry_name
totarget_name
most of this is also done by
shutil.copyfileobj
but it doesn't have a call back for progress eitherthe source of the
ZipFile.extract
method calls_extract_member
uses:where member has be converted from a name to a ZipInfo object by
getinfo(member)
if it wasn't a ZipInfo object抱歉有点晚才看到这个。有类似的问题,需要与 zipfile.Zipfile.extractall 等效的文件。如果您有
tqdm>=4.40.0
(我一年多前发布的),那么:Sorry a bit late seeing this. Had a similar problem, needing an equivalent to
zipfile.Zipfile.extractall
. If you havetqdm>=4.40.0
(which I released over a year ago), then:对于懒人来说,下面是一个基于 Dan D 的回答的独立工作示例。在 Python 3.10.6 上测试。未优化,但有效。
在此示例中,假设目标“test”目录存在,但您当然可以在提取函数中创建它。
与我在本主题中看到的大多数答案相比,丹的答案的优点是,如果存档由非常大的文件组成,则每次处理存档中的文件时显示进度并不能达到目标。
For the lazy, below is a self-contained working example based on Dan D's answer. Tested on Python 3.10.6. Not optimized, but works.
In this example, the assumption is that the target "test" directory exists, but you can of course create it in the extract function.
The advantage of Dan's answer over most of the answers I've seen for this topic is that showing progress each time a file from the archive is processed does not achieve the goal if the archive consists of very large files.