Python, Deleting all files in a folder older than X days

You need to give it the path also or it will look in cwd.. which ironically enough you did on the os.remove but no where else...

for f in os.listdir(path):
    if os.stat(os.path.join(path,f)).st_mtime < now - 7 * 86400:

I think the new pathlib thingy together with the arrow module for dates make for neater code.

from pathlib import Path
import arrow

filesPath = r"C:\scratch\removeThem"

criticalTime = arrow.now().shift(hours=+5).shift(days=-7)

for item in Path(filesPath).glob('*'):
    if item.is_file():
        print (str(item.absolute()))
        itemTime = arrow.get(item.stat().st_mtime)
        if itemTime < criticalTime:
            #remove it
            pass
  • pathlib makes it easy to list the directory contents, to access file characteristics such as as creation times and to get full paths.
  • arrow makes calculations of times easier and neater.

Here's the output showing the full paths offered by pathlib. (No need to join.)

C:\scratch\removeThem\four.txt
C:\scratch\removeThem\one.txt
C:\scratch\removeThem\three.txt
C:\scratch\removeThem\two.txt

os.listdir() returns a list of bare filenames. These do not have a full path, so you need to combine it with the path of the containing directory. You are doing this when you go to delete the file, but not when you stat the file (or when you do isfile() either).

Easiest solution is just to do it once at the top of your loop:

f = os.path.join(path, f)

Now f is the full path to the file and you just use f everywhere (change your remove() call to just use f too).


You need to use if os.stat(os.path.join(path, f)).st_mtime < now - 7 * 86400: instead of if os.stat(f).st_mtime < now - 7 * 86400:

I find using os.path.getmtime more convenient :-

import os, time

path = r"c:\users\%myusername%\downloads"
now = time.time()

for filename in os.listdir(path):
    # if os.stat(os.path.join(path, filename)).st_mtime < now - 7 * 86400:
    if os.path.getmtime(os.path.join(path, filename)) < now - 7 * 86400:
        if os.path.isfile(os.path.join(path, filename)):
            print(filename)
            os.remove(os.path.join(path, filename))