Oct. 08, 2013

Python script to remove /tmp/ files older than 7 days

For no reason at all, I needed a simple trimmer program. Rather than write a shell script in bash, thought to do it in python.

#!/usr/bin/python

# run by crontab
# removes any files in /tmp/ older than 7 days

import os, sys, time
from subprocess import call

now = time.time()
cutoff = now - (7 * 86400)

files = os.listdir("/tmp")
for xfile in files:
        if os.path.isfile( "/tmp/" + xfile ):
                t = os.stat( "/tmp/" + xfile )
                c = t.st_ctime

                # delete file if older than a week
                if c < cutoff:
                        os.remove("/tmp/" + xfile)

Save this as /wherever/trim_tmp.py, and chmod +x it for good measure. Then, add to crontab with crontab -e. In the localized user crontab file, put @daily /wherever/trim_tmp.py

Find this interesting, or useful? Consider sharing the post.

3 responses to “Python script to remove /tmp/ files older than 7 days”

  1. Gregg says:

    Thanks for this, it is really helpful. But one question, shouldn't you avoid using the keyword file?

  2. Dino says:

    Derp, you're right; changing to "xfile" in honor of the 90s.

  3. Mads says:

    find /tmp -mtime 7+

Leave a Reply

Your email address will not be published. Required fields are marked *

Posts on this blog solely represent my personal opinions and technical experience.

© 2009-2017 Edin (Dino) Beslagic