Path.replace是等同于os.replace还是shutil.move?

问题描述 投票:1回答:1

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

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

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

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

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

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

那么,这些功能中的哪一个是Path.replace使用的?是否存在Path.replace失败的风险,因为目标位于不同的文件系统上?

python file-rename pathlib
1个回答
2
投票

如果你看看the source codePath().replace()就是os.replace()

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)
© www.soinside.com 2019 - 2024. All rights reserved.