Python:os.remove() 和 os.unlink() 之间的区别以及使用哪一个?

Python: Difference between os.remove() and os.unlink() and which one to use?

我在一个文件夹中有很多文件。我想在处理完每个文件后将其删除。

使用os.remove()os.unlink有什么区别?哪种方法最适合我的场景?

它们与 official Python 2.7.15 documentation 中描述的相同。

os.remove(path):

Remove (delete) the file path. If path is a directory, OSError is raised; see rmdir() below to remove a directory. This is identical to the unlink() function documented below. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.

Availability: Unix, Windows.

os.unlink(path):

Remove (delete) the file path. This is the same function as remove(); the unlink() name is its traditional Unix name.

Availability: Unix, Windows.

在 Python v3.4 及更高版本中使用 pathlib.Path 文件访问时

虽然该问题特别要求删除 os 模块文件,但最新版本的 Python 有另一个删除文件的选项,可能是替代方法。

直接回答 - 使用 pathlib.Path.unlink()

  • 注:pathlib.Path.remove()不存在

当使用 pathlib module 访问文件时,使用 pathlib.Path.unlink() 删除文件。

Path.unlink() 方法可替代 os.remove()os.unlink()。它直接在 Path 对象上执行,而不是通过 string 参数传递文件的位置。

更多详情

从 Python v3.4 开始,pathlib 内置模块可用于以面向对象的方式处理文件访问。我相信也可以通过 Pip 为旧版本的 Python.

提供单独的软件包

使用 pathlib,您可以创建属于 Path class 的文件夹和文件对象。删除文件的相关方法已合并为 unlink()。他们没有 remove() 方法(可能是因为,根据 shash678 的回答,没有区别,它只是一个别名)。这似乎等同于文件删除的 os 方法,而不是指定文件本身的基本方法。

请参阅 Object Oriented file system paths,以及底部的 table,显示 os.remove()os.unlink() 映射到 Path.unlink()

在Python v3.8 中,missing_ok 参数被添加到Path.unlink() 函数中。当 *missing_ok* == True 时,如果文件在尝试删除之前不存在,则不会引发异常。