• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 528
  • Last Modified:

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?
  • 2
1 Solution
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).
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

koleto115Author Commented:
You are welcome. Also, have a look at the shutil module that implements a lot of functionality that is used in shell scripts (http://docs.python.org/library/shutil.html).
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now