![](/img/trans.png)
[英]os.rename, os.replace and shutil.move errors on windows 10
[英]Is Path.replace equivalent to os.replace or shutil.move?
pathlib.Path.replace
方法的文檔說明:
將此文件或目錄重命名為給定的目標。 如果目標指向現有文件或目錄,它將被無條件替換。
這缺少一些細節。 為了進行比較,這里是os.replace
的文檔:
將文件或目錄
src
重命名為dst
。 如果dst
是目錄,將引發OSError
。 如果dst
存在並且是一個文件,如果用戶有權限,它將被靜默替換。 如果src
和dst
在不同的文件系統上,操作可能會失敗。 如果成功,重命名將是一個原子操作(這是 POSIX 要求)。
重要的部分是“如果src
和dst
在不同的文件系統上,操作可能會失敗” 。 與os.replace
不同的os.replace
,shutil.move
沒有這個問題:
如果目標在當前文件系統上,則使用
os.rename()
。 否則,使用copy_function
將src
復制到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.