如何在Python中删除包括其所有文件的目录?

51

我正在编写一些Python代码。我想在程序结束时删除new_folder以及其中的所有文件。

有人可以指导我如何做吗?我看到过不同的命令,如os.rmdir,但它只会删除路径。以下是我的代码:

for files in sorted(os.listdir(path)):
  os.system("mv "+path+" new_folder")`

上面的代码将移动一个名为check的文件夹到new_folder中。我想从new_folder中删除该check文件夹。


3
可能是如何使用Python删除非空文件夹?的重复问题。 - Mike Scotty
4个回答

92

如果您想要删除该文件

import os
os.remove("path_to_file")

但是使用上面的代码无法删除目录,如果想要删除目录,请使用以下代码

但你不能使用上面的代码来删除目录,如果想要删除目录,则使用以下代码

import os
os.rmdir("path_to_dir")
从上面的命令中,如果目录为空,则可以删除目录,如果目录不为空,则可以使用shutil模块。
import shutil
shutil.rmtree("path_to_dir")

以上所有方法都是Python的方式。如果您了解您的操作系统,那么这种方法取决于操作系统,所有上述方法都不会受到影响。

import os
os.system("rm -rf _path_to_dir")

哦,好吧,这是你做这件事的方法:...但实际上,这才是你做这件事的方法:...但真正的是,这就是你所要求的:... - undefined

33

-2

这是我的方法:

# function that deletes all files and then folder

import glob, os

def del_folder(dir_name):
    
    dir_path = os.getcwd() +  "\{}".format(dir_name)
    try:
        os.rmdir(dir_path)  # remove the folder
    except:
        print("OSError")   # couldn't remove the folder because we have files inside it
    finally:
        # now iterate through files in that folder and delete them one by one and delete the folder at the end
        try:
            for filepath in os.listdir(dir_path):
                os.remove(dir_path +  "\{}".format(filepath))
            os.rmdir(dir_path)
            print("folder is deleted")
        except:
            print("folder is not there")

-4

使用 os.system("rm -rf" + 某个路径 +" 新文件夹")


但我想删除一个在另一个文件夹内的文件夹。 - sara
我想使用类似于的东西。如果 os.path.exists() 那么就删除。 - sara
使用os.system("rm -rf " + path + "/new_folder")命令。此外,如果文件夹不存在,则-f函数不会抛出错误,因此您已经设置好了。 - PMonti
1
最好使用其他答案中建议的shutil.rmtree。如果字符串whatever_path来自不受信任的输入,则此答案打开了执行任意shell命令的可能性。 - Odysseas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接