0

I want this function to delete files. It does this correctly, but it also deletes folders, which I do not want.

I also get an error during execution:

Access is denied: 'C:/temp3\\IDB_KKK

In folder temp3 i have:

IDB_OPP.txt
IDB_KKK - folder

Code:

def delete_Files_StartWith(Path,Start_With_Key):
    my_dir = Path
    for fname in os.listdir(my_dir):
        if fname.startswith(Start_With_Key):
            os.remove(os.path.join(my_dir, fname))

delete_Files_StartWith("C:/temp3","IDB_")
jez
  • 14,867
  • 5
  • 37
  • 64
meitale
  • 137
  • 4
  • 15

4 Answers4

2

Use the following, to check if it is a directory:

os.path.isdir(fname) //if is a directory
Mike B
  • 2,756
  • 2
  • 16
  • 28
1

To remove a directory and all its contents, use shutil.

The shutil module offers a number of high-level operations on files and collections of files.

Refer to the question How do I remove/delete a folder that is not empty with Python?

import shutil

..
    if fname.startswith(Start_With_Key):
        shutil.rmtree(os.path.join(my_dir, fname))
Community
  • 1
  • 1
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • 1
    This may be what the OP wants (given a broad enough interpretation of the trainwreck v.1 text of the question), *or* it may be the opposite of what the OP wants (delete files but *not* folders, as in the interpretation Prune took for the v.2 edit) – jez Aug 25 '16 at 18:41
  • Agreed. If that's the case, the isdir() check is the correct one. – MatsLindh Aug 25 '16 at 18:51
0

Do you want to delete files recursively (i.e. including files that live in subdirectories of Path) without deleting those subdirectories themselves?

import os
def delete_Files_StartWith(Path, Start_With_Key):
    for dirPath, subDirs, fileNames in os.walk(Path):
        for fileName in fileNames: # only considers files, not directories
            if fileName.startswith(Start_With_Key):
                os.remove(os.path.join(dirPath, fileName))
jez
  • 14,867
  • 5
  • 37
  • 64
0

I fixed it by the following:

def delete_Files_StartWith(Path,Start_With_Key):
    os.chdir(Path)
    for fname in os.listdir("."):
        if os.path.isfile(fname) and fname.startswith(Start_With_Key):
            os.remove(fname)

thanks you all.

meitale
  • 137
  • 4
  • 15