Welcome folks today in this blog post we will be
removing all files older than
x days using
os module and
time module in python. All the full source code of the application is given below.
In order to get started you need to make an
app.py file and copy paste the following code
import os import time base_path = 'uploads' def remove_files(dir_path, n): all_files = os.listdir(dir_path) now = time.time() n_days = n * 86400 for f in all_files: file_path = os.path.join(dir_path, f) if not os.path.isfile(file_path): continue if os.stat(file_path).st_mtime < now - n_days: os.remove(file_path) print("Deleted ", f) remove_files(base_path, 4)
Here in this above script it will automatically delete all files which are older than
4 days you can change this value according to your situation.
Now if you execute the above script by typing the below command as shown below