Delete oldest files in directory python3

Viewed 2106

I'm writing a data logging program (security camera) and I need to delete the oldest file(s) in a folder before the disk is full. There will be thousands of files and it is important that any sorting functions aren't going to tie up resources ideally for more then a couple of seconds. I've read through several ideas and seem to have trouble getting them to work (I'm a bit new to python).

So:
Wondering if os.walk is going be relatively slow with a list of thousands or tens of thousands of files?

I'm very intrigued by Matteo Dell'Amico's suggestion (from another site):

min(os.listdir(path), key=os.path.getctime)
max(os.listdir(path), key=os.path.getctime)

I keep getting FileNotFoundError: [Errno 2]..... Perhaps someone could help with the syntax needed to fix this? Ultimately I'm sure there are multiple ways of doing this but I would prefer the most efficient way on system resources. Thanks so much!

edit: I've tried including at the top:

import os
path = "home/pi/Desktop/images/"
3 Answers

The code you copied is retrieving bare names from os.listdir, and passing them directly to os.path.getctime. This doesn't work so well if those names need to be combined with your path to work.

A naive modification to what you're already trying (not using any facilities new to Python 3) might look like:

min(os.listdir(path), key=lambda p: os.path.getctime(os.path.join(path, p)))

If you have log files, you can rotate them. logrotate has options like maxage and the rotate that help you delete automatically.

second option is, if you have files, it's just easier to use find command withing the terminal(writing a shell script and cronjob) to do this efficiently.

third option is, using python code:

os.path.getmtime(filename)

this gives you a timestamp of the modification time of filename, witch you can pull a timedelta on and remove if older than specific time.

Related