Question : How to delete similar files with python?

I would like to delete similar files quietly with some extension under windows with python.

What I have up to now is this:

import os

os.system('del *.log')


But since this is shel command executed it always throw some stupid output if no files with this extension were found. How to delete files quietly from a python module?

Answer : How to delete similar files with python?

Have a look at http://docs.python.org/library/glob.html#glob.glob and http://docs.python.org/library/os.html#os.remove. See the snippet below. Uncomment the last two lines only when you are sure what is going to happen (dangerous operation).
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
import glob
import os
 
path = '.' # working directory
mask = os.path.join(path, '*.log')
print mask
 
# Just to see what it is about...
print glob.glob(mask)
 
# Process the globbed files.
for fname in glob.glob(mask):
    print fname
    ##if os.path.isfile(fname):
    ##    os.remove(fname)    
Open in New Window Select All
Random Solutions  
 
programming4us programming4us