pythondelete-directory

How to delete sub directories in a directory based on their time modified by using python?


based on this script:

 #!/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)

we can delete files in a path based on their time modified, but how can we delete folders in other folders based on their time modification?

it means there are many folders in the main folder but we need to keep main folders and subfolders and only delete folders which their modification time is older than a specific time.


Solution

  • You can try something along these lines

    import shutil, os, time
    
    top_dir = '/tmp'
    
    now = time.time()
    cutoff = now - (7 * 86400)
    
    def del_old_files_and_dirs(top_dir, cutoff_time):
        for root, dirs, files in os.walk(top_dir, topdown=False):
            for cdir in dirs:
                fdir = os.path.join(root, cdir)
                if os.path.getmtime(fdir) < cutoff_time:
                    shutil.rmtree(fdir)
                else:
                    # Process this dir again recursively
                    del_old_files_and_dirs(fdir, cutoff_time)
            for cfile in files:
                ffile = os.path.join(root, cfile)
                if os.path.getmtime(ffile) < cutoff_time:
                      os.remove(ffile)
    
    
    
    del_old_files_and_dirs(top_dir, cutoff)