How to print the percentage of zipping a file python

2024/9/22 1:14:47

I would like to get the percentage a file is at while zipping it. For instance it will print 1%, 2%, 3%, etc. I have no idea on where to start. How would I go about doing this right now I just have the code to zip the file.

Code:

zipPath = zipfile.ZipFile("Files/Zip/" + pic + ".zip", "w")for root, dirs, files in os.walk(filePath):for file in files:zipPath.write(os.path.join(root, file), str(pic) + "\\" + file)print("Done")
zipPath.close()
Answer

Unfortunately, you can't get progress on the compression of each individual file from the zipfile module, but you can get an idea of the total progress by keeping track of how many bytes you've processed so far.

As Mikko Ohtamaa suggested, the easiest way to do this is to walk through the file list twice, first to determine the file sizes, and second to do the compression. However, as Kevin mentioned the contents of the directory could change between these two passes, so the numbers may be inaccurate.

The program below (written for Python 2.6) illustrates the process.

#!/usr/bin/env python''' zip all the files in dirname into archive zipnameUse only the last path component in dirname as the archive directory name for all filesWritten by PM 2Ring 2015.02.15From http://stackoverflow.com/q/28522669/4014959
'''import sys
import os
import zipfiledef zipdir(zipname, dirname):#Get total data size in bytes so we can report on progresstotal = 0for root, dirs, files in os.walk(dirname):for fname in files:path = os.path.join(root, fname)total += os.path.getsize(path)#Get the archive directory namebasename = os.path.basename(dirname)z = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)#Current data byte countcurrent = 0for root, dirs, files in os.walk(dirname):for fname in files:path = os.path.join(root, fname)arcname = os.path.join(basename, fname)percent = 100 * current / totalprint '%3d%% %s' % (percent, path)z.write(path, arcname)current += os.path.getsize(path)z.close()def main():if len(sys.argv) < 3:print 'Usage: %s zipname dirname' % sys.argv[0]exit(1)zipname = sys.argv[1]dirname = sys.argv[2]zipdir(zipname, dirname)if __name__ == '__main__':main()

Note that I open the zip file with the zipfile.ZIP_DEFLATED compression argument; the default is zipfile.ZIP_STORED, i.e., no compression is performed. Also, zip files can cope with both DOS-style and Unix-style path separators, so you don't need to use backslashes in your archive pathnames, and as my code shows you can just use os.path.join() to construct the archive pathname.


BTW, in your code you have str(pic) inside your inner for loop. In general, it's a bit wasteful re-evaluating a function with a constant argument inside a loop. But in this case, it's totally superfluous, since from your first statement it appears that pic is already a string.

https://en.xdnf.cn/q/72001.html

Related Q&A

kafka-python read from last produced message after a consumer restart

i am using kafka-python to consume messages from a kafka queue (kafka version 0.10.2.0). In particular i am using KafkaConsumer type. If the consumer stops and after a while it is restarted i would lik…

Python lib to Read a Flash swf Format File

Im interested in using Python to hack on the data in Flash swf files. There is good documentation available on the format of swf files, and I am considering writing my own Python lib to parse that dat…

PyQt5 Signals and Threading

I watched a short tutorial on PyQt4 signals on youtube and am having trouble getting a small sample program running. How do I connect my signal being emitted from a thread to the main window?import cp…

Pythons hasattr sometimes returns incorrect results

Why does hasattr say that the instance doesnt have a foo attribute?>>> class A(object): ... @property ... def foo(self): ... ErrorErrorError ... >>> a = A() >>…

Pure python library to read and write jpeg format

guys! Im looking for pure python implementation of jpeg writing (reading will be nice, but not necessary) library. Ive founded only TonyJPEG library port at http://mail.python.org/pipermail/image-sig/2…

Conda - unable to completely delete environment

I am using Windows 10 (all commands run as administrator). I created an environment called myenv. Then I used conda env remove -n myenvNow, if I tryconda info --envsI only see the base environment. How…

How to list all function names of a Python module in C++?

I have a C++ program, I want to import a Python module and list all function names in this module. How can I do it?I used the following code to get the dict from a module:PyDictObject* pDict = (PyDict…

Pandas groupby and sum total of group

I have a Pandas DataFrame with customer refund reasons. It contains these example data rows:**case_type** **claim_type** 1 service service 2 service service 3 charg…

Capture webcam video using PyQt

Given the following PyQt code, I can perfectly capture the webcams streaming video. Now, I want to modify code, so a button named capture button is added that once pressed captures the streaming video …

Plot a 3d surface from a list of lists using matplotlib

Ive searched around for a bit, and whhile I can find many useful examples of meshgrid, none shhow clearly how I can get data from my list of lists into an acceptable form for any of the varied ways Ive…