Delete Multiple Files in a Directory in Python



Python provides robust modules for file and directory manipulation, namely the OS and shutil modules. The 'OS' module provides functions for interacting with the operating system. It allows you to perform operations such as creating, removing, and manipulating files and directories, as well as retrieving information about them.

On the other hand, the shutil module offers a higher-level interface for file operations, making tasks like copying, moving, and deleting entire directories straightforward. Below are several methods to delete files and folders.

Deleting Multiple Files

To delete multiple files, we have to loop over a list of filenames and apply the os.remove() function for each.

Example

The following code attempts to delete each specified file. If a file is successfully deleted, a confirmation message is printed. If a file does not exist, an error message is displayed instead.

import os

# List of files to delete
files_to_delete = ['file1.txt', 'file2.txt', 'file3.txt']

# Deleting multiple files
for file_name in files_to_delete:
    try:
        os.remove(file_name)
        print(f'Deleted: {file_name}')
    except FileNotFoundError:
        print(f'File not found: {file_name}')

Following is the output for the above code.

Deleted: file1.txt
Deleted: file2.txt
File not found: file3.txt

Deleting a Single File

To delete a single file, you can use the 'os.remove()' function. This function requires either an absolute or a relative path to the file you wish to delete.

Example

In the following example 'os.remove()' function is called with the filename. If the file exists, it will be deleted, and no output will be generated. If the file does not exist, a FileNotFoundError will be raised.

import os

# Specify the file name (assuming it exists in the current working directory)
file_name = 'my_file.txt'

# Deleting the file
os.remove(file_name)

Following is the output for the above code.

FileNotFoundError: [Errno 2] No such file or directory: 'my_file.txt'

Deleting an Empty Folder

To delete a single empty folder, use can use os.rmdir(), which removes a directory only if it is empty.

Example

In the following example os.rmdir() function deletes the specified directory, but if the directory contains any files or subdirectories, a `DirectoryNotEmptyError` will be raised.

import os

# Specify the folder name (it must be empty)
folder_name = 'my_empty_folder'

# Deleting the empty folder
os.rmdir(folder_name)

Following is the output for the above code.

OSError: [Errno 39] Directory not empty: 'my_empty_folder'

Using Regular Expressions to Delete Specific Files

You can also use regular expressions to match and delete files fitting a specific pattern. This involves using os.walk() to traverse directories.

Example

The following example demonstrates the basic usage of os.walk() function to match and delete files by transverse through the local system's directories.

import os 
import re

# Variables for directory and regex pattern
mypath = 'my_folder'
pattern = r'\.txt$'  # Match all .txt files

# Deleting files matching the regex pattern
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.search(pattern, x), files):
        os.remove(os.path.join(root, file))
        print(f'Deleted: {os.path.join(root, file)}')

Output

Following is the output for the above.

Deleted: my_folder/file1.txt
Deleted: my_folder/file2.txt
Updated on: 2025-02-24T13:23:06+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements