Deleting all files in a directory with Python


I want to delete all files with the extension .bak in a directory. How can I do that in Python?

Asked By: slh2080



First glob them, then unlink.

Via os.listdir and os.remove:

import os

filelist = [ f for f in os.listdir(mydir) if f.endswith(".bak") ]
for f in filelist:
    os.remove(os.path.join(mydir, f))

Using only a single loop:

for f in os.listdir(mydir):
    if not f.endswith(".bak"):
    os.remove(os.path.join(mydir, f))

Or via glob.glob:

import glob, os, os.path

filelist = glob.glob(os.path.join(mydir, "*.bak"))
for f in filelist:

Be sure to be in the correct directory, eventually using os.chdir.

Answered By: miku

Use os.chdir to change directory .
Use glob.glob to generate a list of file names which end it ‘.bak’. The elements of the list are just strings.

Then you could use os.unlink to remove the files. (PS. os.unlink and os.remove are synonyms for the same function.)

#!/usr/bin/env python
import glob
import os
for filename in files:
Answered By: unutbu

you can create a function. Add maxdepth as you like for traversing subdirectories.

def findNremove(path,pattern,maxdepth=1):
    for r,d,f in os.walk(path):
        if r.count(os.sep) - cpath <maxdepth:
            for files in f:
                if files.endswith(pattern):
                        print "Removing %s" % (os.path.join(r,files))
                    except Exception,e:
                        print e
                        print "%s removed" % (os.path.join(r,files))

Answered By: ghostdog74

In Python 3.5, os.scandir is better if you need to check for file attributes or type – see os.DirEntry for properties of the object that’s returned by the function.

import os 

for file in os.scandir(path):

This also doesn’t require changing directories since each DirEntry already includes the full path to the file.

Answered By: Yi Jiang

On Linux and macOS you can run simple command to the shell:'rm /tmp/*.bak', shell=True)
Answered By: Vitaly Zdanevich

I realize this is old; however, here would be how to do so using just the os module…

def purgedir(parent):
    for root, dirs, files in os.walk(parent):                                      
        for item in files:
            # Delete subordinate files                                                 
            filespec = os.path.join(root, item)
            if filespec.endswith('.bak'):
        for item in dirs:
            # Recursively perform this operation for subordinate directories   
            purgedir(os.path.join(root, item))
Answered By: M.Markfort

For one line solution (Both Windows and Linux) ;

import glob,os

for file in glob.glob("<your_path>/*.bak"): print(file," this will be deleted")

if input("continue ?") == "Y":
    for file in glob.glob("<your_path>/*.bak"): os.remove(file)
Answered By: Veysel Olgun
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.