Path.replace 是否等同于 os.replace 或 shutil.move?

Ara*_*Fey 2 python file-rename pathlib

pathlib.Path.replace方法的文档指出:

将此文件或目录重命名为给定的目标。如果目标指向现有文件或目录,它将被无条件替换。

这缺少一些细节。为了进行比较,这里是 的文档os.replace

将文件或目录重命名srcdst. 如果dst是目录, OSError将被引发。如果dst存在并且是一个文件,如果用户有权限,它将被静默替换。如果srcdst位于不同的文件系统上,操作可能会失败。如果成功,重命名将是一个原子操作(这是 POSIX 要求)。

最重要的部分是“操作可能会失败,如果srcdst在不同的文件系统”。不像os.replaceshutil.move没有这个问题:

如果目标在当前文件系统上,则os.rename()使用。否则,src复制到dst使用copy_function然后删除。

那么,这些函数中的哪一个正在Path.replace使用?Path.replace由于目标位于不同的文件系统上,是否有失败的风险?

Bor*_*ris 5

Path(x).replace(y)只是打电话os.replace(x, y)。您可以在源代码中看到这一点:

class _NormalAccessor(_Accessor):
    # [...]
    replace = os.replace
    # [...]

_normal_accessor = _NormalAccessor()

# [...]

class Path(PurePath):
    # [...]
    def _init(self,
              # Private non-constructor arguments
              template=None,
              ):
        self._closed = False
        if template is not None:
            self._accessor = template._accessor
        else:
            self._accessor = _normal_accessor

    # [...]

    def replace(self, target):
        """
        Rename this path to the given path, clobbering the existing
        destination if it exists.
        """
        if self._closed:
            self._raise_closed()
        self._accessor.replace(self, target)
Run Code Online (Sandbox Code Playgroud)