0

I have a hundred zipfiles in a directory and so I did a python script to unzip all files, but I needed to display a percentage status of each file inside of anyone huge zipfile (actually each zipfile has only one file).

I found some examples here but in all of them each zipfile had several files inside it therefore the percentage was about the number of files inside of zipfile and not about one of them (my case).

So, I wrote the code below, but for each zipfile I just got to show "100% completed" but I should showing for each file, something like that:

10% Completed 12% Completed 16% Completed ... 100% Completed

I really appreciate any suggestion.

# -- 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
4

2 回答 2

0

这是一个示例代码片段,您可以使用它来修改您的代码。它使用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))
于 2013-07-29T03:02:48.280 回答
0

extract方法直接写入磁盘。没关系,但你想参与其中。extract您可能想要使用 ,而不是使用open。使用open,您将从中获得一个类似文件的对象,并且您可以从该文件复制到磁盘上的文件,并随时写出进度。

于 2013-07-28T23:20:32.420 回答