[英]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.