Categories
Python

Python – remove oldest files in a directory, only a defined count of them remains

By experimenting with the Pi camera and PIR at may Raspberry Pi were quickly many images written to the SD card.

In order to get some control, the following Python Script is a good basis.
There is the possibility to specify a directory and the maximum number of files stored in it.

Exceeds the number of files the defined value, older files are deleted.

In my case, I always keep a maximum of 1000 images in the folder.

Sample code:

#!/usr/bin/python
 
import os
 
path = "/home/pi/pictures/"
max_Files = 1000
 
def sorted_ls(path):
    mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
    return list(sorted(os.listdir(path), key=mtime))
 
del_list = sorted_ls(path)[0:(len(sorted_ls(path))-max_Files)]
 
for dfile in del_list:
    os.remove(path + dfile)