I'm fairly new to python and I need to get a list of all first level subdirectories sorted inversely by last access date that I can crawl through. The point is I'm writing a cleaning function that receives a variable containing the amount of megabytes to free. It should then walk through all first-level subdirectories and list them according to their last accessed date. Then the function should start deleting them until the needed amount of megabytes is relieved.
My code so far:
import os
def cleanSpace(megs,path="/var/lib/mpd/music/"):
list = []
for root, dir, file in os.walk(path):
this_path = os.path.join(root, dir)
stat = os.stat(this_path)
this_atime = stat.st_atime
this_size = round(stat.st_size/1048576)
list.append([this_path,this_atime,this_size])
sort(list, key=lambda x: x[1], reverse=True)
total_freed = 0
for folder in list:
if total_freed < megs:
#os.unlink(folder[0])
print(folder[0])
total_freed += folder[2]
else:
print("Total freed space:",total_freed)
break