TOC

Python 删除文件

平时删除文件都是 os.unlink 和 os.remove 中随便选一个,今天突然想看看这两个方法有什么不一样。

remove 和 unlink 实际上来自 Modules/posixmodule.c
可以看到这两个方法实际上相同。

/*[clinic input]
os.remove = os.unlink
Remove a file (same as unlink()).
If dir_fd is not None, it should be a file descriptor open to a directory,
  and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
  If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/

static PyObject *
os_remove_impl(PyObject *module, path_t *path, int dir_fd)
/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
{
    return os_unlink_impl(module, path, dir_fd);
}

Python 3 的 Path 对象中也有一个 unlink 方法(pathlib.Path.unlink):

def unlink(self, missing_ok=False):
    """
    Remove this file or link.
    If the path is a directory, use rmdir() instead.
    """
    try:
        os.unlink(self)
    except FileNotFoundError:
        if not missing_ok:
            raise

顺便对删除目录做一个整理:

# os.remove(path: StrOrBytesPath, *, dir_fd: int | None = ...)
# os.unlink(path: StrOrBytesPath, *, dir_fd: int | None = ...)

os.mkdir(path: StrOrBytesPath, mode: int = ..., *, dir_fd: int | None = ...)
os.rmdir(path: StrOrBytesPath, *, dir_fd: int | None = ...)

os.makedirs(name: StrOrBytesPath, mode: int = ..., exist_ok: bool = ...)
os.removedirs(name: StrOrBytesPath)

pathlib.Path.rmdir -> os.rmdir

shutil.rmtree(path, ignore_errors=False, onerror=None, *, dir_fd=None)