Python 3 Automation Script to Delete All Files Inside a Directory Older than X Days Using OS and Time Modules Full Project For Beginners

Python 3 Automation Script to Delete All Files Inside a Directory Older than X Days Using OS and Time Modules Full Project For Beginners

 

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.

 

 

Get Started

 

 

In order to get started you need to make an app.py file and copy paste the following code

 

app.py

 

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.

See also  Python Tkinter GUI Script to Make Language Translate App Using Google Translate API Full Project For Beginners

 

Now if you execute the above script by typing the below command as shown below

 

python app.py

 

Leave a Reply