Deleting files of specific extension using * in Python

Viewed 3252

I have couple of text files named as:

temp1.txt
temp2.txt
temp3.txt
temp4.txt
track.txt

I want to delete files only starting with temp and ending with .txt. I tried using os.remove("temp*.txt") but I'm getting error as:

The filename, directory name, or volume label syntax is incorrect: 'temp*.txt'

What is the right way to do this using python 3.7?

4 Answers
from pathlib import Path

for filename in Path(".").glob("temp*.txt"):
    filename.unlink()

For your question, you can take a look at the methods of built-in function str. Just check what the filename starts and ends with like:

>>> name = "temp1.txt"
>>> name.startswith("temp") and name.endswith("txt")
True

Then you can use a for loop with os.remove():

for name in files_list:
    if name.startswith("temp") and name.endswith("txt"):
        os.remove(name)

Use os.listdir() or str.split() to create the list.

This pattern matching can be done by using glob module. And pathlib is one more alterantive if you don't want to use os.path module

import os 
import glob
path = os.path.join("/home", "mint", "Desktop", "test1") # If you want to manually specify path
print(os.path.abspath(os.path.dirname(__file__)))   # To get the path of current directory 
print(os.listdir(path)) # To verify the list of files present in the directory 
required_files = glob.glob(path+"/temp*.txt") # This gives all the files that matches the pattern
print("required_files are ", required_files)
results = [os.remove(x) for x in required_files]
print(results)
import glob


# get a recursive list of file paths that matches pattern  
fileList = glob.glob('temp*.txt', recursive=True)    
# iterate over the list of filepaths & remove each file. 

for filePath in fileList:
    try:
        os.remove(filePath)
    except OSError:
        print("Error while deleting file")
Related