This is another solution to a previously asked question. The project outline:
It’s not uncommon for a few unneeded but humongous files or folders to take up the bulk of the space on your hard drive. If you’re trying to free up room on your computer, you’ll get the most bang for your buck by deleting the most massive of the unwanted files. But first you have to find them.
Write a program that walks through a folder tree and searches for exceptionally large files or folders—say, ones that have a file size of more than 100MB. (Remember that to get a file’s size, you can use os.path.getsize() from the os module.) Print these files with their absolute path to the screen.
My solution:
import send2trash, os
import pyinputplus as pyip
def get_size(basedir, find_size):
large_folders = {}
large_files = {}
for folder, subfolders, filenames in os.walk(basedir):
folder_size = 0
for filename in filenames:
filepath = os.path.join(folder, filename)
folder_size += os.path.getsize(filepath)
file_size = os.path.getsize(filepath)
if file_size > find_size:
large_files[filepath] = file_size
if folder_size > find_size:
large_folders[folder] = folder_size
return large_folders, large_files
def main():
while True:
basedir = input("Please enter a folder to search: ")
if not os.path.exists(basedir):
print("This path does not exist.")
continue
else:
find_size = pyip.inputInt(prompt="Enter the size in bytes of the folders and files to file: ")
large_folders, large_files = get_size(basedir, find_size)
print("Large folders:")
for folder, size in large_folders.items():
print(f"{folder} is {size} bytes")
print("Large files:")
for file, size in large_files.items():
print(f"{file} is {size} bytes")
while True:
deletedir = input("Enter the directory of the file or folder you want to delete, or enter nothing to choose another folder to search: ")
if not deletedir:
break
elif not os.path.exists(deletedir):
print("This path does not exist.")
continue
else:
print("Deleting path...")
send2trash.send2trash(deletedir)
continue
if __name__ == '__main__':
main()