Delete Files Matching Pattern in Python Example

04-Nov-2022

.

Admin

Delete Files Matching Pattern in Python Example

Hi Dev,

This simple article demonstrates of Delete Files Matching Pattern in Python Example. This tutorial will give you simple example of How to Remove Files with Matching Pattern in Python. This article goes in detailed on Remove Files Python Wildcard. In this article, we will implement a Python Delete Files with Wildcard. Let's get started with Python Remove Files 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.

so let's see following examples 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 2: 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

#Python