tags:

views:

851

answers:

5

I know how to delete single files, however I am lost in my implementation of how to delete all files in a directory of one type.

Say the directory is \myfolder

I want to delete all files that are .config files, but nothing to the other ones. How would I do this?

Thanks Kindly

A: 

I would do something like the following:

import os
files = os.listdir("myfolder")
for f in files:
  if not os.path.isdir(f) and ".config" in f:
    os.remove(f)

It lists the files in a directory and if it's not a directory and the filename has ".config" anywhere in it, delete it. You'll either need to be in the same directory as myfolder, or give it the full path to the directory. If you need to do this recursively, I would use the os.walk function.

Dan Wolchonok
I actually meant files, not folders. Sorry Dan
Not your fault - but this answer is now irrelevant due to OP editing the question.
Triptych
Still a good example of iterating!
note that this will delete files like 'my.config.bak'. Probably not what the OP wants.
Triptych
A: 

Use os.path and splitext to assist in getting the file type.

tathamr
+5  A: 

Use the glob module:

import os
from glob import glob

for f in glob ('myfolder/*.config'):
   os.unlink (f)
eduffy
+1: Yep, glob is the right approach here (if you don't want to walk sub-directories, of course -- that would need os.walk).
Alex Martelli
A: 

Here ya go:

import os

# Return all files in dir, and all its subdirectories, ending in pattern
def gen_files(dir, pattern):
   for dirname, subdirs, files in os.walk(dir):
      for f in files:
         if f.endswith(pattern):
            yield os.path.join(dirname, f)


# Remove all files in the current dir matching *.config
for f in gen_files('.', '.config'):
   os.remove(f)

Note also that gen_files can be easily rewritten to accept a tuple of patterns, since str.endswith accepts a tuple

Triptych
A: 

Hi,

I am having an issue while using glob.glob. It is reading all files from th desired folder and writing to the new zip file but the problem is that it is, however, adding subdirectories, but not adding files form the subdirectories.

Here is my code:

for name in (Source_Dir):
    for name in glob.glob("/path/to/source/dir/*" ):
        myZip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)

myZip.close()
Akash