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_")
1
  • Shortened wording, fixed sentence structure, improved code formatting. Commented Aug 25, 2016 at 18:09

4 Answers 4

2

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

os.path.isdir(fname) //if is a directory
Sign up to request clarification or add additional context in comments.

Comments

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))

2 Comments

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)
Agreed. If that's the case, the isdir() check is the correct one.
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))

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.