如何删除文件或文件夹?


当前回答

您可以使用内置的pathlib模块(需要Python 3.4+,但PyPI上有旧版本的后端:pathlib、pathlib2)。

要删除文件,可以使用unlink方法:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

或使用rmdir方法删除空文件夹:

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()

其他回答

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

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

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

!rm -r my_dir

传统上,您使用shutil:

import shutil
shutil.rmtree(my_dir) 

我个人的偏好是使用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.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))

对于删除文件:

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