如何删除文件或文件夹?


当前回答

对于删除文件:

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

其他回答

用于删除文件的Python语法

import os
os.remove("/tmp/<file_name>.txt")

or

import os
os.unlink("/tmp/<file_name>.txt")

or

用于Python的pathlib库版本>=3.4

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink(missing_ok=False)

用于删除文件或符号链接的Unlink方法。

如果missing_ok为false(默认值),则在路径不存在时引发FileNotFoundError。如果missing_ok为true,则将忽略FileNotFoundError异常(行为与POSIX rm-f命令相同)。在版本3.8中更改:添加了missing_ok参数。

最佳实践

首先,检查文件或文件夹是否存在,然后将其删除。可以通过两种方式实现:

os.path.isfile(“/path/to/file”)使用异常处理。

os.path.isfile示例

#!/usr/bin/python
import os

myfile = "/tmp/foo.txt"
# If file exists, delete it.
if os.path.isfile(myfile):
    os.remove(myfile)
else:
    # If it fails, inform the user.
    print("Error: %s file not found" % myfile)

异常处理

#!/usr/bin/python
import os

# Get input.
myfile = raw_input("Enter file name to delete: ")

# Try to delete the file.
try:
    os.remove(myfile)
except OSError as e:
    # If it fails, inform the user.
    print("Error: %s - %s." % (e.filename, e.strerror))

各自的输出

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.

Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.

Enter file name to delete : foo.txt

用于删除文件夹的Python语法

shutil.rmtree()

shutil.rmtree()示例

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir = raw_input("Enter directory name: ")

# Try to remove the tree; if it fails, throw an error using try...except.
try:
    shutil.rmtree(mydir)
except OSError as e:
    print("Error: %s - %s." % (e.filename, e.strerror))

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


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

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

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

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

如何在Python中删除文件或文件夹?

对于Python 3,要单独删除文件和目录,请分别使用unlink和rmdir Path对象方法:

from pathlib import Path
dir_path = Path.home() / 'directory' 
file_path = dir_path / 'file'

file_path.unlink() # remove file

dir_path.rmdir()   # remove directory

请注意,您也可以对Path对象使用相对路径,并且可以使用Path.cwd检查当前工作目录。

有关在Python 2中删除单个文件和目录的信息,请参阅下面标记的部分。

要删除包含内容的目录,请使用shutil.rmtree,并注意这在Python 2和3中可用:

from shutil import rmtree

rmtree(dir_path)

集会示威

Python 3.4中的新功能是Path对象。

让我们使用一个来创建一个目录和文件来演示用法。请注意,我们使用/来连接路径的部分,这可以解决操作系统之间的问题以及在Windows上使用反斜杠的问题(您需要将反斜杠加倍,如\\或使用原始字符串,如r“foo\bar”):

from pathlib import Path

# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()

file_path = directory_path / 'file'
file_path.touch()

现在:

>>> file_path.is_file()
True

现在让我们删除它们。首先文件:

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False

我们可以使用globbing删除多个文件-首先让我们为此创建几个文件:

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()

然后只需遍历glob模式:

>>> for each_file_path in directory_path.glob('*.my'):
...     print(f'removing {each_file_path}')
...     each_file_path.unlink()
... 
removing ~/directory/foo.my
removing ~/directory/bar.my

现在,演示如何删除目录:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

如果我们想删除目录和其中的所有内容呢?对于此用例,请使用shutil.rmtree

让我们重新创建目录和文件:

file_path.parent.mkdir()
file_path.touch()

注意,除非rmdir为空,否则它会失败,这就是为什么rmtree如此方便的原因:

>>> directory_path.rmdir()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
    self._accessor.rmdir(self)
  File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
    return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'

现在,导入rmtree并将目录传递给函数:

from shutil import rmtree
rmtree(directory_path)      # remove everything 

我们可以看到整个事情都被删除了:

>>> directory_path.exists()
False

Python 2

如果您使用的是Python 2,则有一个名为pathlib2的pathlib模块的后端,可以使用pip安装:

$ pip install pathlib2

然后可以将库别名为pathlib

import pathlib2 as pathlib

或者直接导入Path对象(如下所示):

from pathlib2 import Path

如果太多,可以使用os.remove或os.unlink删除文件

from os import unlink, remove
from os.path import join, expanduser

remove(join(expanduser('~'), 'directory/file'))

or

unlink(join(expanduser('~'), 'directory/file'))

并且可以使用os.rmdir删除目录:

from os import rmdir

rmdir(join(expanduser('~'), 'directory'))

注意,还有一个os.removedirs-它只递归地删除空目录,但可能适合您的用例。

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