How to Delete Files Using Python Code

It’s really easy to delete a single file in Python. Say the file you want to delete is called “MyFile.txt.” You could delete it using this syntax:

import os
 
os.remove("MyFile.txt")

Let’s say you had many files in a directory, and the ones you wanted to delete were called MyFile1.txt, MyFile2.txt, and MyFile3.txt. One trick that you can use to delete such files is to use a wildcard pattern, such as MyFile*.txt. The * indicates that any sequence of characters can fill that space. Using the following code, you could find all files in a directory that match this pattern and then delete them:

import os, glob
 
for filePath in glob.glob("MyDirectory/MyFile*.txt"):
    if os.path.isfile(filePath):
        os.remove(filePath)

If you wanted to do this for all subdirectories, you could do the following:

import os, glob
 
for root, dirs, files in os.walk('MyDirectory'):
    for filePath in glob.glob(os.path.join(root, "MyFile*.txt")):
        if os.path.isfile(filePath):
            os.remove(filePath)

Just be careful! Any time you are using wildcards to delete files, it is possible to delete files you didn’t intend to. So make sure you test thoroughly before implementing code like this.

Leave a Reply