删除文件开头

2024-04-23 15:59:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要这个函数来删除文件。它可以正确地执行此操作,但它也会删除我不需要的文件夹。在

我在执行过程中也会遇到一个错误:

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

在temp3文件夹中,我有:

^{pr2}$

代码:

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

Tags: pathkey函数文件夹osmydirwith
3条回答

要删除目录及其所有内容,use ^{}。在

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

参考问题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))

是否要递归地删除文件(即包括位于Path子目录的文件),而不删除这些子目录本身?在

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

使用以下命令检查它是否是一个目录:

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

相关问题 更多 >