How to delete all files in a directory with Python?


When it comes to file management within a directory in Python, there can be scenarios where you find yourself needing to entirely empty the folder, erasing all the files and sometimes subdirectories it contains. In this regard, Python makes provision for several efficient and secure methods to accomplish this task. In this article, we'll explore a few diverse methods to achieve the above-mentioned objective of deleting all files in a directory. We take the help of code examples accompanied by step-by-step explanations to ensure a smooth execution of the aforementioned task.

Utilizing os.listdir() and os.remove()

Let's start with os.listdir() and os.remove() functions from the os module. The versatile Python os module makes available to us functions to interact with the operating system and also work with file operations. By utilizing os.listdir(), we can compile a list of all files in the directory and then traverse through the list to delete each file using the os.remove() method.

Deleting all files in directory using os.listdir() and os.remove().

In the first example, the delete_files_in_directory() function accepts the directory path as its parameter. The os.listdir() method is deployed to gather a comprehensive compilation of all the files within the specified directory. Then it proceeds to iterate through the list of files, conducting checks to ensure each item is indeed a file (not a directory), and by making use of os.remove(), the files are deleted.

Example

import os

def delete_files_in_directory(directory_path):
   try:
     files = os.listdir(directory_path)
     for file in files:
       file_path = os.path.join(directory_path, file)
       if os.path.isfile(file_path):
         os.remove(file_path)
     print("All files deleted successfully.")
   except OSError:
     print("Error occurred while deleting files.")

# Usage
directory_path = '/path/to/directory'
delete_files_in_directory(directory_path)

Output

For a certain directory, the following was the output

All files deleted successfully.

Using os.scandir() and os.unlink()

Next, we utilize the functions os.scandir() and os.unlink() from os module. In Python 3.5, the introduction of os.scandir(), heralded the surpassing efficiency of os.listdir() when dealing with large directories. Empowered by this function, we proceed to retrieve file information and deploy os.unlink() to delete all files in the directory.

Deleting all files in a directory using os.scandir() and os.unlink().

In this example, we make use of the os.scandir() function within a "with" statement, to automatically close the directory after all files are deleted. This grants us swift access to file properties, and we delete all files in the directory in an elegant way utilizing the function os.unlink().

Example

import os

def delete_files_in_directory(directory_path):
   try:
     with os.scandir(directory_path) as entries:
       for entry in entries:
         if entry.is_file():
            os.unlink(entry.path)
     print("All files deleted successfully.")
   except OSError:
     print("Error occurred while deleting files.")

# Usage
directory_path = '/path/to/directory'
delete_files_in_directory(directory_path)

Output

For a certain directory, the following was the output

All files deleted successfully.

Using glob.glob() and os.remove()

The Python glob module offers a convenient way to find all files matching a specific pattern. By employing glob.glob(), we can obtain a list of all files in the directory matching a certain pattern and then delete them one by one.

Deleting all files in a directory using glob.glob() and os.remove().

Moving on, we call upon the Python glob module and its glob.glob() function to find all files in the directory, utilizing the * wildcard to match all files. We then delete each file one by one using os.remove() function.

Example

import os
import glob

def delete_files_in_directory(directory_path):
   try:
     files = glob.glob(os.path.join(directory_path, '*'))
     for file in files:
       if os.path.isfile(file):
         os.remove(file)
     print("All files deleted successfully.")
   except OSError:
     print("Error occurred while deleting files.")

# Usage
directory_path = '/path/to/directory'
delete_files_in_directory(directory_path)

Output

For a certain directory, the following was the output

All files deleted successfully.

Using os.scandir() and shutil.rmtree()

Now, in times of need, when the call arises to remove not just files in a directory but also all of its subdirectories, we call upon Python shutil module, to provide us a method called shutil.rmtree().

Deleting all files and subdirectories in a directory using os.scandir() and shutil.rmtree().

The os.scandir() method iterates over all the entries in the directory, inspecting each entity to differentiate between files and subdirectories. In this process, os.unlink() is made use of to delete the files, while the power of shutil.rmtree() method is used to delete the subdirectories.

Example

import os
import shutil

def delete_files_and_subdirectories(directory_path):
   try:
     with os.scandir(directory_path) as entries:
       for entry in entries:
         if entry.is_file():
            os.unlink(entry.path)
         else:
            shutil.rmtree(entry.path)
     print("All files and subdirectories deleted successfully.")
   except OSError:
     print("Error occurred while deleting files and subdirectories.")

# Usage
directory_path = '/path/to/directory'
delete_files_and_subdirectories(directory_path)

Output

For a certain directory with subdirectories, the following was the output

All files and subdirectories deleted successfully.

Using os.walk() and os.remove()

Lastly, we replicate the same task that we have been doing by using the os.walk() and os.remove() functions.

Deleting files all files and subdirectories in a directory using os.walk() and os.remove().

The os.walk() function offers a powerful way to navigate up and down a directory tree, enabling efficient processing of files in a directory and its subdirectories. By utilizing os.walk(), we delete all files in a directory and its subdirectories.

Example

import os

def delete_files_in_directory_and_subdirectories(directory_path):
   try:
     for root, dirs, files in os.walk(directory_path):
       for file in files:
         file_path = os.path.join(root, file)
         os.remove(file_path)
     print("All files and subdirectories deleted successfully.")
   except OSError:
     print("Error occurred while deleting files and subdirectories.")

# Usage
directory_path = '/path/to/directory'
delete_files_in_directory_and_subdirectories(directory_path)

Output

For a certain directory with subdirectories, the following was the output

All files and subdirectories deleted successfully.

In conclusion, we have traversed five distinct paths to delete all files in a directory using Python. Each method bears its unique allure, awaiting your discerning choice. Nonetheless, be cautious, as file deletion is a permanent action. Remember to test your code on a test directory before executing any delete operations on critical data.

Updated on: 03-Aug-2023

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements