删除一个文件或文件夹

如何在 Python 中删除一个文件或文件夹?

解决办法

os.remove() 删除一个文件。

os.rmdir() 删除一个空目录。

shutil.rmtree() 删除一个目录和其所有内容。


来自 Python 3.4+ pathlib 模块的 Path 对象也暴露了这些实例方法。

评论(5)

使用

shutil.rmtree(path[, ignore_errors[, onerror]])

(见shutil上的完整文档)和/或

os.remove

os.rmdir

(完整的文档在os上。)

评论(1)

为你们创建一个功能。

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))
评论(2)