How to delete all files in a folder older than n days using Python

How to delete all files in a folder older than n days using Python:

In this post, we will learn how to delete files older than n days in Python. This program has many practical uses. For example, if you are using a server and saving the server logs in different files in a folder, you can use this program to delete all log files which are older than specific days. You can run a python script automatically daily and delete the old log files automatically.

Python is best for automating boring tasks. You can use this script with your own system as well. We will learn different ways to do that. But, you can use any of these methods that we are explaining below.

Method 1: By using os and time modules:

We can use the os and time modules to do this.

  • Get the path.
  • Get the list of all files and folders in that path.
  • Iterate through the paths one by one.
  • Check if the path is a file path or not.
  • If yes, check the time difference between the file created and the current time.
    • If this difference is more than the given days, delete the file.

Let’s take a look at the program:

import os
import time


def delete_old_files(root_dir_path, days):
    files_list = os.listdir(root_dir_path)
    current_time = time.time()
    for file in files_list:
        file_path = os.path.join(root_dir_path, file)
        if os.path.isfile(file_path):
            if (current_time - os.stat(file_path).st_birthtime) > days * 86400:
                os.remove(file_path)


if __name__ == '__main__':
    delete_old_files('/Users/username/Downloads/', 7)
  • This program is removing all files created more than 7 days before.
  • delete_old_files method is iterating through the files and deleting the old files.
  • os.listdir method is used to list down all files in a directory. We are saving the current epoch time in seconds in current_time.
  • The for loop is iterating through the file list. It appends the file path to the end of the root directory.
  • If the path is a file, i.e. if os.path.isfile returns True for a path, it uses os.stat.st_birthtime to get the created time and checks if the created time is before 7 days or not. If yes, it removes that file.

Method 2: By using os.walk and datetime:

We can use os.walk to iterate through the files in a folder and datetime module to record the current time.

import os
from datetime import datetime


def delete_old_files(root_dir_path, days):
    current_time = datetime.utcnow().timestamp()
    for _, _, files_list in os.walk(root_dir_path):
        for file in files_list:
            file_path = os.path.join(root_dir_path, file)
            if os.path.isfile(file_path):
                if (current_time - os.stat(file_path).st_birthtime) > days * 86400:
                    os.remove(file_path)


if __name__ == '__main__':
    delete_old_files('/Users/username/Downloads/', 7)

It will work in the same way.

You can use any of these methods. Both will give the same result.

You might also like: