簡體   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