Python - deleting old files

I'm a little new to python and trying to figure it out on my own, but only getting the pieces so far. Basically I am looking for a script that will recursively search the directory and its subdirectories and delete files that are at least 24 hours old but do not change directories. Any tips or examples are appreciated.

thanks

+8
python
source share
2 answers

Os.walk is used for a recursive directory search . For each file, it checks the changed date using os.path.getmtime and compares this with datetime.now (current time). datetime.timedelta is built to create a timedelta in 24 hours.

It looks for the os.path.curdir directory, which is the current directory when the script is called. You can set dir_to_search to something else, for example. script parameter.

 import os import datetime dir_to_search = os.path.curdir for dirpath, dirnames, filenames in os.walk(dir_to_search): for file in filenames: curpath = os.path.join(dirpath, file) file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath)) if datetime.datetime.now() - file_modified > datetime.timedelta(hours=24): os.remove(curpath) 
+28
source share

If you need to recursively check all files in all directories, something like this should do:

 import os, time path = "/path/to/folder" def flushdir(dir): now = time.time() for f in os.listdir(dir): fullpath = os.path.join(dir, f) if os.stat(fullpath).st_mtime < (now - 86400): if os.path.isfile(fullpath): os.remove(fullpath) elif os.path.isdir(fullpath): flushdir(fullpath) flushdir(path) 
+5
source share

All Articles