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?

You sort files by
ctimenot alphabetically so don't assume the oldest file will befile_1. Let's see this using a simplified version of your code:First run (no files):
Seconds run (old files already exist):
As you can see the oldest file during second run is
file_6. That's because when disk usage is above the threshold, we enter theifbranch where we sort and list existing files, only 1-4 files were created at that point so 5-10 are still older.Please also note that
ctimeis the time of the last metadata change on UNIX systems (file ownership, permissions, not a content modification). You can trymtimeto sort by a modification date.The index issue should be also fixed now after the logic in the code has been slightly changed.
Note: example is using Python 3.7+