Skip to content

Instantly share code, notes, and snippets.

@CodeByAidan
Last active May 7, 2023 19:13
Show Gist options
  • Select an option

  • Save CodeByAidan/15c0da21e29c40190fa9c77eb5de8ae7 to your computer and use it in GitHub Desktop.

Select an option

Save CodeByAidan/15c0da21e29c40190fa9c77eb5de8ae7 to your computer and use it in GitHub Desktop.
Delete a directory with Python! When windows is not fast enough some times, resort to using programming! Works with Python2.x and Python3.x Usage: python fast_delete.py <directory_path>
from __future__ import print_function
import os
import shutil
import sys
import time
from concurrent.futures import ThreadPoolExecutor
import six
alternative = [
(1024 ** 5, " PB"),
(1024 ** 4, " TB"),
(1024 ** 3, " GB"),
(1024 ** 2, " MB"),
(1024 ** 1, " KB"),
(1024 ** 0, (" byte", " bytes")),
]
def size(bytes, system):
for factor, suffix in system:
if bytes >= factor:
break
amount = int(bytes / factor)
if isinstance(suffix, tuple):
singular, multiple = suffix
suffix = singular if amount == 1 else multiple
return str(amount) + suffix
def delete_file(file_path):
try:
file_size = os.path.getsize(file_path)
os.remove(file_path)
return file_size
except Exception as e:
print("Error deleting file: {}. Error: {}".format(file_path, e))
return 0
def fast_delete(path):
total_size = 0
deleted_size = 0
count = 0
start_time = time.time()
total_files = 0
for root, dirs, files in os.walk(path):
total_files += len(files)
for name in files:
file_path = os.path.join(root, name)
total_size += os.path.getsize(file_path)
with ThreadPoolExecutor() as executor:
for root, dirs, files in os.walk(path, topdown=False):
for name in files:
file_path = os.path.join(root, name)
deleted_size += executor.submit(delete_file, file_path).result()
count += 1
progress = (deleted_size / total_size) * 100 if total_size > 0 else 0
time_elapsed = time.time() - start_time
time_remaining = (time_elapsed / count) * (total_files - count) if count > 0 else 0
sys.stdout.write(
"Progress: {:.2f}% | Files: {}/{} | Deleted Size: {} / {} | Time remaining: {:.2f} seconds\r".format(
progress, count, total_files, size(deleted_size, system=alternative), size(total_size, system=alternative), time_remaining
)
)
sys.stdout.flush()
for name in dirs:
dir_path = os.path.join(root, name)
try:
shutil.rmtree(dir_path)
except Exception as e:
print("Error deleting directory: {}. Error: {}".format(dir_path, e))
print(
"\nDeleted {} items and {} in {:.2f} seconds.".format(
count, size(deleted_size, system=alternative), time.time() - start_time
)
)
if len(sys.argv) < 2:
print("Usage: python fast_delete.py <path>")
else:
fast_delete(sys.argv[1])
if __name__ == "__main__":
fast_delete(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment