How to Delete Files Matching Pattern in Python?

Published On: 25/03/2025 | Category: Python

Delete Files Matching Pattern in Python

Hi Guys,

In this tutorial, I'll show you how to delete files that match a specific pattern using Python. You will learn how to use Python's built-in libraries like os and glob to remove multiple files in one go based on a pattern, such as files with a certain extension (e.g., `.txt`). This guide will walk you through the process of deleting files using wildcard patterns in Python.

We'll use the remove() method from the os library to delete individual files, and the glob() method to gather a list of file paths matching a specific pattern. Let's dive in with an example:

Example:

In this example, I created a few files inside a folder named files. We will remove all the files with the `.txt` extension:

files/test.txt
files/demo.txt
files/first.png
main.py
import os, glob
    
# Getting All Files List
fileList = glob.glob('files/*.txt', recursive=True)
      
# Remove all files one by one
for file in fileList:
    try:
        os.remove(file)
    except OSError:
        print("Error while deleting file")
  
print("Removed all matched files!")
Output:

The following files will be removed:

files/test.txt
files/demo.txt

This script will help you delete multiple files matching a specific pattern quickly and easily. You can also customize the script to remove files with other extensions or even perform recursive deletion in subdirectories.

Happy Pythonic Coding!

Frequently Asked Questions (FAQ)

1. How do I delete all files with a certain extension in Python?

You can use the glob module to list all files matching the extension, and then use the os.remove() function to delete them.

2. Can I delete files recursively in subdirectories?

Yes, you can set the recursive=True flag in the glob.glob() method to include files from subdirectories.

3. What if the file I want to delete is in use?

If the file is open or in use, the os.remove() function may raise an OSError. Make sure the file is not being used by another process before attempting to delete it.

4. How can I delete all files in a directory?

To delete all files in a directory, you can use glob with a wildcard pattern such as 'files/*', which matches all files in the directory.

5. Is it possible to add confirmation before deleting a file in Python?

Yes, you can add a prompt or a user confirmation step before calling os.remove() to ensure files are not accidentally deleted.

I hope this helps you efficiently delete files matching a pattern in Python!