I want to delete all files with the extension bak
in a directory. How can I do that in Python?
views:
191answers:
4
+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
2010-01-03 16:02:54
Solved. Thank you very much.
slh2080
2010-01-03 16:16:32
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
2010-01-03 16:47:33
@slh2080 Since you say the problem has been solved, why not mark the answer as the correct answer?
blwy10
2010-01-03 17:00:36
@dragonjujo, yes i know, but i thought it would be clearer this way ..
The MYYN
2010-01-03 17:12:18
+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
2010-01-03 16:06:33
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
2010-01-04 01:30:12