Search code examples
pythonpython-2.7directoryprogress

Folder/ Directory delete with progress


I am writing an application using pyqt. There is a requirement to delete a folder which contain sub folders and many files. The path to folder is residing in usb disk. While the deletion is going on, I would like to show the users with updated progress bar. Here is the sample code I tried to calculate percentage while deletion is going on.

#!/usr/bin/python2.7
import subprocess
import os

def progress_uninstall_dir():
    uninstall_path = "path/to/folder"
    usb_mount = "path/to/usb/mount"
    if not os.path.exists(uninstall_path):
        print ("Directory not found.")
    else:
        proc=subprocess.Popen("du -ck " + usb_mount + " | grep total | cut -f 1", shell=True, stdout=subprocess.PIPE, )
        inintial_usb_size = int(proc.communicate()[0])
        proc=subprocess.Popen("du -ck " + uninstall_path + " | grep total | cut -f 1", shell=True, stdout=subprocess.PIPE, )
        folder_size_to_remove = int(proc.communicate()[0])
        delete_process = subprocess.Popen('rm -rf ' + uninstall_path,  shell=True)
        while delete_process.poll() is None:
            proc=subprocess.Popen("du -ck " + usb_mount + " | grep total | cut -f 1", shell=True, stdout=subprocess.PIPE, )
            current_size =   int(proc.communicate()[0])
            diff_size = int(inintial_usb_size - current_size)
            percentage = float(diff_size/folder_size_to_remove)*100
            print (percentage)


progress_uninstall_dir()

However, the above code always give 0 as percentage. Any help would be appreciated.


Solution

  • Your problem might be due to integer division when calculating percentage. The code you have right now divides one integer by another (presumably obtaining the value 0) and then converts the result to a float. You'd be better served by converting one of the two integers to float before the division:

    percentage = float(diff_size)/folder_size_to_remove*100