GH-73991: Add pathlib.Path.move() (#122073)

Add a `Path.move()` method that moves a file or directory tree, and returns a new `Path` instance pointing to the target.

This method is similar to `shutil.move()`, except that it doesn't accept a *copy_function* argument, and it doesn't check whether the destination is an existing directory.
This commit is contained in:
Barney Gale 2024-08-25 16:51:51 +01:00 committed by GitHub
parent aa905925e1
commit 625d0705b9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 225 additions and 4 deletions

View file

@ -14,7 +14,7 @@ resemble pathlib's PurePath and Path respectively.
import functools
import operator
import posixpath
from errno import EINVAL
from errno import EINVAL, EXDEV
from glob import _GlobberBase, _no_recurse_symlinks
from stat import S_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO
from pathlib._os import copyfileobj
@ -928,6 +928,25 @@ class PathBase(PurePathBase):
"""
raise UnsupportedOperation(self._unsupported_msg('replace()'))
def move(self, target):
"""
Recursively move this file or directory tree to the given destination.
"""
self._ensure_different_file(target)
try:
return self.replace(target)
except UnsupportedOperation:
pass
except TypeError:
if not isinstance(target, PathBase):
raise
except OSError as err:
if err.errno != EXDEV:
raise
target = self.copy(target, follow_symlinks=False, preserve_metadata=True)
self.delete()
return target
def chmod(self, mode, *, follow_symlinks=True):
"""
Change the permissions of the path, like os.chmod().