如何删除文件或文件夹?


当前回答

下面是一个同时使用os.remove和shutil.rmtree的健壮函数:

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path) or os.path.islink(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))

其他回答

删除文件夹中的所有文件

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)

删除目录中的所有文件夹

from shutil import rmtree
import os

// os.path.join()  # current working directory.

for dirct in os.listdir(os.path.join('path/to/folder')):
    rmtree(os.path.join('path/to/folder',dirct))

Use

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

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

os.remove

and

os.rmdir

(操作系统的完整文档)

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)

我个人的偏好是使用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库的作者。

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

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')