June 27, 2022

Python Program to Delete Files Having a Specific Extension

In this tutorial we’ll see how to write a Python program to delete all the files having a specific extension.

1. Using os.listdir()

In os module in Python there is a function listdir() that returns a list containing the names of the entries in the directory. You can iterate that list to look for file names that ends with a specific extension and delete those files.

We’ll use the directory structure as given below for the program

Test
    abc.txt
    abc1.txt
    newimage.png
    Sub1 (D)
          sub1.txt
    Sub2 (D)
          sub2.txt
def delete_files(dir_path):
    path = os.listdir(dir_path);
    for entry in path:
        print(entry)
        if entry.endswith(".txt"):
            p = os.path.join(dir_path, entry)
            print('Deleting', p)
            os.remove(p)

delete_files("F:\knpcode\Python\Test")
Output
abc.txt
Deleting F:\knpcode\Python\Test\abc.txt
abc1.txt
Deleting F:\knpcode\Python\Test\abc1.txt
newimage.png
Sub1
Sub2

As you can see files with extension .txt in the directory Test are deleted. This program doesn’t delete files recursively in the sub-directories. If you want to delete files having specific extension in sub-directories too then you can make the above Python program to call function recursively or you can use functions in glob module.

Python program to delete files having specific extension recursively
def delete_files(dir_path):
    path = os.listdir(dir_path);
    for entry in path:
        print(entry)
        p = os.path.join(dir_path, entry)
        if os.path.isdir(p):
            print('Directory', p)
            # recursive call
            delete_files(p)
        else:
            if p.endswith(".txt"):
                print('Deleting', p)
                os.remove(p)
Output
abc.txt
Deleting F:\knpcode\Python\Test\abc.txt
abc1.txt
Deleting F:\knpcode\Python\Test\abc1.txt
newimage.png
Sub1
Directory F:\knpcode\Python\Test\Sub1
sub1.txt
Deleting F:\knpcode\Python\Test\Sub1\sub1.txt
Sub2
Directory F:\knpcode\Python\Test\Sub2
sub2.txt
Deleting F:\knpcode\Python\Test\Sub2\sub2.txt

2. Using glob() module in Python

The glob module finds all the pathnames matching a specified pattern. You can use this module to find files with specific extension and delete them. In glob module there are functions glob() (returns a list) and iglob() (returns an iterator) that return matching pathnames.

In glob or iglob you can pass an argument recursive=True, If recursive is true, the pattern “**” will match any files and zero or more directories and subdirectories. By default recursive has the value false.

def delete_files(dir_path, ext):
    file_itr = glob.glob(dir_path + '/*' + ext, recursive=True)
    for entry in file_itr:
        print('Deleting', entry)
        os.remove(entry)


delete_files("F:\knpcode\Python\Test\**", ".txt")
Output
Deleting F:\knpcode\Python\Test\abc.txt
Deleting F:\knpcode\Python\Test\abc1.txt
Deleting F:\knpcode\Python\Test\Sub1\sub1.txt
Deleting F:\knpcode\Python\Test\Sub2\sub2.txt

That's all for the topic Python Program to Delete Files Having a Specific Extension. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment