tags:

views:

191

answers:

4

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

A: 

First glob them, then unlink.

Ignacio Vazquez-Abrams
+10  A: 

Via os.listdir and os.remove:

import os

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

Or via glob.glob:

import glob, os

filelist = glob.glob("*.bak")
for f in filelist:
    os.remove(f)

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

The MYYN
Solved. Thank you very much.
slh2080
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
@slh2080 Since you say the problem has been solved, why not mark the answer as the correct answer?
blwy10
@dragonjujo, yes i know, but i thought it would be clearer this way ..
The MYYN
+3  A: 

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)
unutbu
Solved. Thank you very much.
slh2080
A: 

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")
ghostdog74