如何删除文件或文件夹?


当前回答

为了避免Éric Araujo评论中强调的TOCTOU问题,您可以捕捉一个异常来调用正确的方法:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

因为shutil.rmtree()将只删除目录,os.remove()或os.unlink()将仅删除文件。

其他回答

如果您喜欢编写一段漂亮且可读的代码,我建议使用子流程:

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

如果你不是软件工程师,那么可以考虑使用Jupyter;您可以简单地键入bash命令:

!rm -r my_dir

传统上,您使用shutil:

import shutil
shutil.rmtree(my_dir) 

这是我删除目录的功能。“路径”需要完整的路径名。

import os

def rm_dir(path):
    cwd = os.getcwd()
    if not os.path.exists(os.path.join(cwd, path)):
        return False
    os.chdir(os.path.join(cwd, path))

    for file in os.listdir():
        print("file = " + file)
        os.remove(file)
    print(cwd)
    os.chdir(cwd)
    os.rmdir(os.path.join(cwd, path))
import os

folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)

for f in fileList:
    filePath = folder + '/'+f

    if os.path.isfile(filePath):
        os.remove(filePath)

    elif os.path.isdir(filePath):
        newFileList = os.listdir(filePath)
        for f1 in newFileList:
            insideFilePath = filePath + '/' + f1

            if os.path.isfile(insideFilePath):
                os.remove(insideFilePath)

os.remove()删除文件。os.rmdir()删除空目录。shutil.rmtree()删除目录及其所有内容。


Python 3.4+pathlib模块中的路径对象还公开了以下实例方法:

pathlib.Path.unlink()删除文件或符号链接。pathlib.Path.rmdir()删除空目录。

对于删除文件:

os.unlink(path, *, dir_fd=None)

or

os.remove(path, *, dir_fd=None)

这两个函数在语义上是相同的。此函数用于删除文件路径。若路径不是文件,而是目录,则引发异常。

删除文件夹:

shutil.rmtree(path, ignore_errors=False, onerror=None)

or

os.rmdir(path, *, dir_fd=None)

为了删除整个目录树,可以使用shutil.rmtree()。os.rmdir仅在目录为空且存在时有效。

对于向父级递归删除文件夹:

os.removedirs(name)

它使用self删除每个空的父目录,直到父目录包含一些内容

例如,如果目录为空,os.removedirs('abc/xyz/pqr')将按“abc/xyz/pqr”、“abc/xy z”和“abc”的顺序删除目录。

有关更多信息,请查看官方文档:os.unlink、os.remove、os.rmdir、shutil.rmtree、os.removedirs