如何删除文件或文件夹?


当前回答

Use

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

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

os.remove

and

os.rmdir

(操作系统的完整文档)

其他回答

shutil.rmtree是异步函数,所以如果你想检查它何时完成,你可以使用while。。。环

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')
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()删除空目录。

我个人的偏好是使用pathlib对象——它提供了一种与文件系统交互的更具Python性和更少出错的方式,尤其是在您开发跨平台代码时。

在这种情况下,您可以使用pathlib3x-它提供了最新的(在编写此答案时为Python 3.10.a0)Python路径库,用于Python 3.6或更高版本,以及一些附加功能,如“copy”、“copy2”、“copy tree”和“rmtree”等。。。

它还包装shutil.rmtree:

$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib

# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)

# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)

你可以在github或PyPi上找到它


免责声明:我是pathlib3x库的作者。

对于删除文件:

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