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
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):
if os.stat(file_path).st_mtime < now - n_days:
print("Deleted ", f)
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