[英]Is Path.replace equivalent to os.replace or shutil.move?
The documentation of the pathlib.Path.replace
method states: pathlib.Path.replace
方法的文档说明:
Rename this file or directory to the given target.将此文件或目录重命名为给定的目标。 If target points to an existing file or directory, it will be unconditionally replaced.如果目标指向现有文件或目录,它将被无条件替换。
This lacks a bit of detail.这缺少一些细节。 For comparison, here's the documentation of os.replace
:为了进行比较,这里是os.replace
的文档:
Rename the file or directory
src
todst
.将文件或目录src
重命名为dst
。 Ifdst
is a directory,OSError
will be raised.如果dst
是目录,将引发OSError
。 Ifdst
exists and is a file, it will be replaced silently if the user has permission.如果dst
存在并且是一个文件,如果用户有权限,它将被静默替换。 The operation may fail ifsrc
anddst
are on different filesystems.如果src
和dst
在不同的文件系统上,操作可能会失败。 If successful, the renaming will be an atomic operation (this is a POSIX requirement).如果成功,重命名将是一个原子操作(这是 POSIX 要求)。
The important part being "The operation may fail if src
and dst
are on different filesystems" .重要的部分是“如果src
和dst
在不同的文件系统上,操作可能会失败” 。 Unlike os.replace
,shutil.move
does not have this problem:与os.replace
不同的os.replace
,shutil.move
没有这个问题:
If the destination is on the current filesystem, then
os.rename()
is used.如果目标在当前文件系统上,则使用os.rename()
。 Otherwise,src
is copied todst
usingcopy_function
and then removed.否则,使用copy_function
将src
复制到dst
,然后删除。
So, which of these functions is Path.replace
using?那么, Path.replace
使用了这些函数中的Path.replace
? Is there any risk of Path.replace
failing because the destination is on a different file system?由于目标位于不同的文件系统上,是否存在Path.replace
失败的风险?
Path(x).replace(y)
just calls os.replace(x, y)
. Path(x).replace(y)
只是调用os.replace(x, y)
。 You can see this in the source code :您可以在源代码中看到这一点:
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.