繁体   English   中英

监控python中的zip文件提取(显示百分比)

[英]Monitoring zip file extraction (display percentage) in python

我在目录中有一百个zip文件,所以我做了一个python脚本来解压缩所有文件,但是我需要在任何巨大的zip文件中显示每个文件的百分比状态(实际上每个zipfile只有一个文件)。

我在这里找到了一些示例,但是在所有这些示例中,每个zipfile中都有几个文件,因此百分比与zipfile中的文件数量有关,而不是其中一个(我的情况)。

因此,我编写了以下代码,但是对于每个zip文件,我只显示了“ 100%完成”,但是我应该为每个文件显示类似的内容:

10%完成12%完成16%完成... 100%完成

我真的很感谢任何建议。

# -- coding: utf-8 --

import glob, zipfile, sys, threading
from os.path import getsize

class Extract(threading.Thread):
      def __init__(self, z, fname, base, lock):
          threading.Thread.__init__(self)
          self.z = z
          self.fname = fname
          self.base = base
          self.lock = lock

      def run(self):
          self.lock.acquire()
          self.z.extract(self.fname, self.base)
          self.lock.release()

if len(sys.argv) < 2:
   sys.exit("""
Sintaxe : python %s [Nome da Pasta]
""" % sys.argv[0])

base = sys.argv[1]
if base[len(base)-1:] != '/':
   base += '/'

for fs in glob.glob(base + '*.zip'):
    if 'BR' not in fs.split('.'):
       f = open(fs,'rb')
       z = zipfile.ZipFile(f)
       for fname in z.namelist():
           size = [s.file_size for s in z.infolist() if s.filename == fname][0]
           lock = threading.Lock()
           background = Extract(z, fname, base, lock)
           background.start()
           print fname + ' => ' + str(size)
           while True:
                 lock.acquire()
                 filesize = getsize(base + fname)
                 lock.release()
                 print "%s %% completed\r" % str(filesize * 100.0 / size)
                 if filesize == size:
                    break

extract方法直接写入磁盘。 没关系,但是您想了解一下。 与其使用extract ,不如使用open 借助open ,您将得到一个类似文件的对象,然后可以从该文件复制到磁盘上的文件,随时随地写出进度。

这是您可以用来修改代码的示例代码片段。 它使用ZipInfo对象查找成员文件的未压缩大小。 阅读时,您可以报告完成情况。

请注意,这是针对Python 3.2及更高版本编写的; 然后添加了with语句支持。 在以前的版本中,您需要打开zip文件并手动将其关闭。

from zipfile import ZipFile

chunk_size = 1024 * 1024
zip_path = "test_zip.zip"
with ZipFile(zip_path, 'r') as infile:
    for member_info in infile.infolist():
        filename = member_info.filename
        file_size = member_info.file_size
        with open("{}_{}".format(zip_path, filename), 'wb') as outfile:
            member_fd = infile.open(filename)
            total_bytes = 0
            while 1:
                x = member_fd.read(chunk_size)
                if not x:
                    break
                total_bytes +=outfile.write(x)
                print("{0}% completed".format(100 * total_bytes / file_size))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM