How to delete old files in python
We will delete files from the directory if there are more than a certain number of them.
The functions will be useful when taking screenshots in python.
The function of collecting files in a folder
files = []
directory = os…listdir(path)
directory.sort(reverse=True)
for file in directory:
if file…endswith(‘.jpg’):
files.append(file)
return files
Let’s assume that our files were saved via timestamp… An example is in the article Optimizing screenshots in python. This is necessary to sort them correctly.
Delete old files function
We will delete files if there are more than 30 of them. The old ones will be deleted first.
def remove_old_files(path, files):
“” “Keeps the last 30 files, deletes the rest” “”
max_files = thirty
if len(files) < max_files:
return
i = 0
for f in files:
i += 1
if i > max_files:
os…remove(os…path…join(path, f))
Using
path = ‘public / build / screenshots’
files = get_files(path)
remove_old_files(path, files)