I have to delete the oldest file in dir when the newest added file exceed the used space limit. I don't know why the sorted list files = sorted(os.listdir(DIR), key=os.path.getctime)
do not contain on first element the oldest file ( in this case file named 'file_1')
code
print('START: Cycle no. ', cycle)
time.sleep(1)
print('Saving {0} files. {1} MB each'.format(FILES_NUM, MB_FILE_SIZE))
i = 1
while (i < FILES_NUM):
usage = psutil.disk_usage(DIR)
used = usage.used // (2**20)
# print('Uzyta pamiec: ', used)
if (used < 50): # 50 MB
print('Saving file_{}'.format(i))
with open("file_{}".format(i), 'wb') as f:
f.write(os.urandom(FILE_SIZE))
else:
files = sorted(os.listdir(DIR), key=os.path.getctime)
print('Files list: ', files)
os.remove(files[0])
print('Deleted oldest file: ',files[0])
i = i + 1
print('KONIEC: Cycle no. ', cycle)
print('Deleting the content of the card...')
results
EDIT:
I know that the next file after deletion should have the ending in the file name one larger than the previous addition. In this example should be Saving file_22
instead of Saving file_23
. The 22nd 'i' is used in deletion process, but how can I overcome this issue?