meitale
meitale

Reputation: 157

Delete file start with

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

Upvotes: 0

Views: 1129

Answers (4)

meitale
meitale

Reputation: 157

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.

Upvotes: 0

MatsLindh
MatsLindh

Reputation: 52902

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

Upvotes: 1

jez
jez

Reputation: 15369

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

Upvotes: 0

Mike B
Mike B

Reputation: 2784

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

os.path.isdir(fname) //if is a directory

Upvotes: 2

Related Questions