Python Delete Files Matching Pattern Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Python Delete Files with Specific Extension Example
- Python Delete Directory if Exists Example
- Python Delete File if Exists Example
- Python Post Request with pem File Example
- Python Post Request with Json File Example
- Python Post Request with Basic Authentication Example
- Python Post Request with Bearer Token Example
- Python Get File Extension from Filename Example
- Python Create Zip Archive from Directory Example
- How to Check if Today is Sunday or not in Python?
- How to Check if Today is Thursday or not in Python?
- How to Check if Today is Wednesday or not in Python?