ItSolutionStuff.com

Python Delete Files Matching Pattern Example

By Hardik Savani • October 30, 2023
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: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Python Delete Files with Specific Extension Example

Read Now →

Python Delete Directory if Exists Example

Read Now →

Python Delete File if Exists Example

Read Now →

Python Post Request with pem File Example

Read Now →

Python Post Request with Json File Example

Read Now →

Python Post Request with Basic Authentication Example

Read Now →

Python Post Request with Bearer Token Example

Read Now →

Python Get File Extension from Filename Example

Read Now →

Python Create Zip Archive from Directory Example

Read Now →

How to Check if Today is Sunday or not in Python?

Read Now →

How to Check if Today is Thursday or not in Python?

Read Now →

How to Check if Today is Wednesday or not in Python?

Read Now →