170

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

2

9 Answers 9

320

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"):
        continue
    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:
    os.remove(f)

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

6
  • 22
    Your first example is using redundant for loops. You can one pass with - [ os.remove(f) for f in os.listdir(".") if f.endswith(".bak") ] - as list comprehensions are meant to be used. Or you can move the 'if' in the comprehension into the for loop - for f in os.listdir("."): if f.endswith(".bak"): os.remove(f)
    – dragonjujo
    Jan 3, 2010 at 16:47
  • @slh2080 Since you say the problem has been solved, why not mark the answer as the correct answer?
    – blwy10
    Jan 3, 2010 at 17:00
  • 6
    Watch out the os.listdir(".")!!! I used this code and forgot to change the path, all my code were gone!!! Tried two different utilities to recover but with no luck!!
    – Lei Guo
    Nov 29, 2016 at 3:51
  • @LeiGuo Fixed that.
    – yugr
    Oct 8, 2017 at 6:49
  • @dragonjujo I would argue that invoking side effects are very much not how list comprehensions are meant to be used.
    – marcelm
    Oct 27, 2020 at 10:41
28

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):
    if file.name.endswith(".bak"):
        os.unlink(file.path)

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

3
  • You're missing a colon, the first line inside the for loop should be if file.name.endswith(".bak"):
    – TSeymour
    Mar 3, 2017 at 18:38
  • Thanks! That'll teach me to write code without actually running them
    – Yi Jiang
    Mar 4, 2017 at 1:40
  • hi, how to create path object ? Aug 9, 2021 at 15:13
26

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
directory='/path/to/dir'
os.chdir(directory)
files=glob.glob('*.bak')
for filename in files:
    os.unlink(filename)
0
8

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

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

path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")
0
2

First glob them, then unlink.

1
  • Link-only answer. Answers should contain the relevant part. If the link is removed, this is just a comment. How to Answer "First glob them, then unlink." seems like a LQA or NAA. Mar 29 at 22:10
1

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'):
                os.unlink(filespec)
        for item in dirs:
            # Recursively perform this operation for subordinate directories   
            purgedir(os.path.join(root, item))
0

For one line solution (Both Windows and Linux) ;

import glob,os

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

if input("continue ?") == "Y":
    for file in glob.glob("<your_path>/*.bak"): os.remove(file)
0

Or using pathlib.Path:

from pathlib import Path

for file in Path("/path/to/folder").glob("*"):
    file.unlink()

This way one also could specify to only delete files that match the glob pattern. For example: .glob("*.txt") to only remove text files.

And for a recursive removal of all files in subfolders just use rglob instead of glob. The following would delete all txt-files in the specified folder and all it's subfolders:

for file in Path("/path/to/folder").rglob("*.txt"):
    file.unlink()
-1

On Linux and macOS you can run simple command to the shell:

subprocess.run('rm /tmp/*.bak', shell=True)
3
  • 4
    Not a good choice in my opinion. It's not portable and it's probably more expensive due to the extra subprocess. Better to use Python APIs.
    – Haakon
    Feb 16, 2018 at 21:40
  • 2
    this solution is platform dependent, whereas Python is platform agnostic. Sep 24, 2020 at 12:14
  • On the other hand, not being able to empty a directory with a single command is insane, so this is simple and elegant.
    – alcalde
    Dec 28, 2023 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.