Python script written in 2021 to detect big files that are unused from a certain amount of time to assist the user clean and manage disk space.
It logs and produces a txt report containing the list of files based on a date (by default datetime(2021, 2, 1)
) and a byte size (by default 47185920).
If the size of a file in the file system is greather than the parametric size and the last modification occurred before the parametric date, then it's logged into the report,
so the user can decide if remove it freeing disk space or keep it.
import time
import math
from datetime import datetime
import os
from os.path import expanduser
home = expanduser("~")
last_date = datetime(2021, 2, 1)
min_size = 47185920
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
reportFile = open("report_{0}.txt".format(datetime.now().strftime("%Y_%m_%d")), 'w')
for subdir, dirs, files in os.walk(home):
for file in files:
analyzedFile = os.path.join(subdir, file)
try:
if last_date > datetime.fromtimestamp(os.path.getmtime(analyzedFile)):
b = os.path.getsize(analyzedFile)
if b > min_size:
print(analyzedFile)
modificationTime = time.strftime('%d/%m/%Y', time.localtime(os.path.getmtime(analyzedFile)))
print("Last edit: {0}".format(modificationTime))
print("Size: {0}".format(convert_size(b)))
print("----------------")
reportFile.write("{0}\n".format(analyzedFile))
reportFile.write("Last edit: {0}\n".format(modificationTime))
reportFile.write("Size: {0}\n".format(convert_size(b)))
reportFile.write("----------------\n")
except WindowsError as e:
pass
reportFile.close()