How to Delete Files Older than X Days in Python

By Birtchum Thompson | March 12, 2020

In this tutorial, we will create a Python script that will delete all files in a directory that are older than x number of days.

It is often necessary to delete files within a directory that are older than a particular number of days. This is especially the case with archive directories. Without performing routine maintenance, these archives can begin consuming large amounts of disk space. Creating a script to remove older archives makes the maintenance process fast and painless.

The first step in creating the script is to add the shebang (path to the Python executable) and the needed package imports.


The next step is to declare a few variables. This script will delete all files and directories within a specified directory that are older than 5 days. To do this, multiply 86400 (number of seconds in a day) by 5. This value will be subtracted from the current time stamp. The directory in which to search for old files is also declared.


Now its time for the heavy lifting. The rest of the script will rely heavily on the os module to list the contents of the directory, determine if an object in the directory is a file or directory, create file paths, and delete files. The shutil module will be used to remove directories. The script will loop over each object in the directory, create its file path, compare its created time to the timestamp created above, and remove the object appropriately. After adding this logic to the script, it is complete.

Share this Content

Join the Discussion

Also Read

UFW, Ubuntu, and firewall logos on dark grey background
Allow SMB in UFW

Allow SMB traffic in UFW on Ubuntu & Debian.

Blue KDE Logo
Configure Screen Locking Shortcut in KDE

Learn to configure the screen locking shortcut in KDE.

Python logo and red trash can
Delete Files Older than X Days in Python

Create a Python script to delete files older than x days.

White Bash Logo
Check Exit Status of Bash Command

Check a Bash command exit status in a script.