繁体   English   中英

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

[英]Is Path.replace equivalent to os.replace or shutil.move?

pathlib.Path.replace方法的文档说明:

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

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

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

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

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM