Delete files older than N days in Python
Last Updated :
26 Apr, 2025
In this article, we will learn to delete files that are older than a given number of days using Python. This work can be done manually but it is difficult to do when files are more in number, so we will use Python to make this task simple. We will learn three ways to do this task using Python:
- Delete files using OS and time modules
- Delete files using os.walk and DateTime
- Delete files using shutil.rmtree of Shutil Module.
Deleting files using os and time modules
File Structure of directory where code exists.
File Structure of demo directory (this folder will be used for testing code) before running code.
Code Implementation:
Importing the necessary modules and Defining the folder in which the action must be done. The N stands for the number of days. The folder where we need to do the delete operation should be changed to the current working directory. Obtain a list of every file that exists in the specified directory hence Check whether or not each file is older than N days by looping through all of them. Delete any file that is more than N number of days old.
Python3
# importing required modules
import os
import time
# folder is the name of the folder in which we
# have to perform the delete operation
folder = "demo"
# N is the number of days for which
# we have to check whether the file
# is older than the specified days or not
N = 3
# changing the current working directory
# to the folder specified
os.chdir(os.path.join(os.getcwd(), folder))
# get a list of files present in the given folder
list_of_files = os.listdir()
# get the current time
current_time = time.time()
# "day" is the number of seconds in a day
day = 86400
# loop over all the files
for i in list_of_files:
# get the location of the file
file_location = os.path.join(os.getcwd(), i)
# file_time is the time when the file is modified
file_time = os.stat(file_location).st_mtime
# if a file is modified before N days then delete it
if(file_time < current_time - day*N):
print(f" Delete : {i}")
os.remove(file_location)
Output:
File Structure of demo directory after running code.
File Structure of directory where code exists:
File Structure of demo directory (this folder will be used for testing code) before running code.
Code Implementation:
Import the required modules. Define the folder in which we have to perform the operation. Define the value of N which is the number of days. Define a function to perform the delete operation based on the condition. Loop using os.walk to check all files one by one. Get the modification time of each file using datetime module. If any file is older than N days then delete it.
Python3
# importing required modules
import os
import datetime
# folder is the name of the folder in which we have to perform the delete operation
folder = "demo"
# N is the number of days for which we have to check whether the file is older than the specified days or not
N = 3
# function to perform delete operation based on condition
def check_and_delete(folder):
# loop to check all files one by one
# os.walk returns 3 things: current path, files in the current path, and folders in the current path
for (root,dirs,files) in os.walk(folder, topdown=True):
for f in files:
# temp variable to store path of the file
file_path = os.path.join(root,f)
# get the timestamp, when the file was modified
timestamp_of_file_modified = os.path.getmtime(file_path)
# convert timestamp to datetime
modification_date = datetime.datetime.fromtimestamp(timestamp_of_file_modified)
# find the number of days when the file was modified
number_of_days = (datetime.datetime.now() - modification_date).days
if number_of_days > N:
# remove file
os.remove(file_path)
print(f" Delete : {f}")
# call function
check_and_delete(folder)
Output:
File Structure of demo directory after running code.
Deleting files using shutil.rmtree
File Structure of directory where code exists:
File Structure of demo directory (this folder will be used for testing code) before running code.
Code Implementation:
Import required modules and define the folder in which we have to perform the operation. Define the value of N which is the number of days. Change the current working directory to the folder in which we have to perform the delete operation. Get a list of all files present in the given directory. Loop over all the files and check whether they are older than N days or not. If any file is older than N days then delete it using os.remove(). If any folder is older than N days then delete it using shutil.rmtree().
Python3
# importing required modules
import os
import time
import shutil
# folder is the name of the folder in which
# we have to perform the delete operation
folder = "demo"
# N is the number of days for which we have
# to check whether the file is older
# than the specified days or not
N = 3
# changing the current working
# directory to the folder specified
os.chdir(os.path.join(os.getcwd(), folder))
# get a list of files present in the given folder
list_of_files = os.listdir()
# get the current time
current_time = time.time()
# "day" is the number of seconds in a day
day = 86400
# loop over all the files
for i in list_of_files:
# get the location of the file
file_location = os.path.join
(os.getcwd(), i)
# file_time is the time when
# the file is modified
file_time = os.stat
(file_location).st_mtime
# if a file is modified before N
# days then delete it
if(file_time < current_time - day*N):
print(f" Delete : {i}")
# if it is a file then
# delete using os.remove
if os.path.isfile(file_location):
os.remove(file_location)
# if it is a folder then delete
# using shutil.rmtree
elif os.path.isdir(file_location):
shutil.rmtree(file_location)
Output:
File Structure of demo directory after running code.
Similar Reads
How to delete a CSV file in Python?
In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
2 min read
How to delete from a pickle file in Python?
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it âserializesâ the object first before writing it to file. Pickling is a way to convert a python object (list, dic
3 min read
How to delete data from file in Python
When data is no longer needed, itâs important to free up space for more relevant information. Python's file handling capabilities allow us to manage files easily, whether it's deleting entire files, clearing contents or removing specific data.For more on file handling, check out:File Handling in Pyt
3 min read
Delete pages from a PDF file in Python
In this article, We are going to learn how to delete pages from a pdf file in Python programming language. Introduction Modifying documents is a common task performed by many users. We can perform this task easily with Python libraries/modules that allow the language to process almost any file, the
4 min read
How to automatically delete/remove files older than x days in Linux
Linux operating systems are widely used for web servers and other data-heavy tasks such as penetration testing etc. In these applications, there can be an accumulation of files that are not useful after a certain period. Now Linux, being an operating system used mostly for its automation functionali
9 min read
How to Delete files in Python using send2trash module?
In this article, we will see how to safely delete files and folders using the send2trash module in Python. Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently deleting them. The OS module's unlink(), remove() and rmdir() functions can be used to delete files or fol
2 min read
Date Time Expression (dte) module in python
In this article, we will discuss how to process and work with dates and time using the Python in command line. Python provides dte module for the same. This module has the following features - It recognizes english month, week and locale names.It works in the highest unit appearing first - 2021 - 12
2 min read
Python - List Files in a Directory
Sometimes, while working with files in Python, a problem arises with how to get all files in a directory. In this article, we will cover different methods of how to list all file names in a directory in Python.Table of ContentWhat is a Directory in Python?How to List Files in a Directory in PythonLi
8 min read
Python - List files in directory with extension
In this article, we will discuss different use cases where we want to list the files with their extensions present in a directory using python. Modules Usedos: The OS module in Python provides functions for interacting with the operating system.glob: In Python, the glob module is used to retrieve fi
3 min read
Interact with files in Python
Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complica
6 min read