Python Delete Files Matching Pattern Example

By Hardik Savani October 30, 2023 Category : Python

Hi,

This tutorial will provide example of python delete files matching pattern. it's simple example of python delete multiple files wildcard. This post will give you simple example of python delete files with wildcard. you will learn python remove files wildcard. Here, Creating a basic example of remove files python wildcard.

In this example, we will use remove() and glob() of "os" library to delete files with wildcard. so let's see below example and do it.

remove() will remove file on given path.

glob() will give you files path recursively.

You can use these examples with python3 (Python 3) version.

let's see below simple example with output:

Example 1: Remove Files with ".txt" Extension

I have created following files on files folder and remove files with ".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:

Removed Files Lists

files/test.txt
files/demo.txt

Example 1: Remove Files with "copy*.txt" Pattern Matching

I have created following files on files folder and remove files with "copy*.txt" pattern matching:

files/copy-test.txt
files/copy-demo.txt
files/demo.txt

main.py

import os, glob
    
# Getting All Files List
fileList = glob.glob('files/copy*.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:

Removed Files Lists

files/copy-test.txt
files/copy-demo.txt

I hope it can help you...

Tags :
Shares