如何删除文件或文件夹?


当前回答

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

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)

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

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

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


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

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

Use

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

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

os.remove

and

os.rmdir

(操作系统的完整文档)

为了避免É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()将仅删除文件。