aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Lib/pathlib/_abc.py
diff options
context:
space:
mode:
authorBarney Gale <barney.gale@gmail.com>2024-08-26 14:14:23 +0100
committerGitHub <noreply@github.com>2024-08-26 14:14:23 +0100
commitc68a93c582cc733c399a1cf9e850e5071f79aec1 (patch)
tree7cf68402c646cd8c5341af70eaf4f5ce9672cbdc /Lib/pathlib/_abc.py
parentdbc1752d4107532d312c78263212e807a3674eb1 (diff)
downloadcpython-c68a93c582cc733c399a1cf9e850e5071f79aec1.tar.gz
cpython-c68a93c582cc733c399a1cf9e850e5071f79aec1.zip
GH-73991: Add `pathlib.Path.copy_into()` and `move_into()` (#123314)
These two methods accept an *existing* directory path, onto which we join the source path's base name to form the final target path. A possible alternative implementation is to check for directories in `copy()` and `move()` and adjust the target path, which is done in several `shutil` functions. This behaviour is helpful in a shell context, but less so in a stored program that explicitly specifies destinations. For example, a user that calls `Path('foo.py').copy('bar.py')` might not imagine that `bar.py/foo.py` would be created, but under the alternative implementation this will happen if `bar.py` is an existing directory.
Diffstat (limited to 'Lib/pathlib/_abc.py')
-rw-r--r--Lib/pathlib/_abc.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/Lib/pathlib/_abc.py b/Lib/pathlib/_abc.py
index 93758b1c71c..0c76480063e 100644
--- a/Lib/pathlib/_abc.py
+++ b/Lib/pathlib/_abc.py
@@ -904,6 +904,24 @@ class PathBase(PurePathBase):
on_error(err)
return target
+ def copy_into(self, target_dir, *, follow_symlinks=True,
+ dirs_exist_ok=False, preserve_metadata=False, ignore=None,
+ on_error=None):
+ """
+ Copy this file or directory tree into the given existing directory.
+ """
+ name = self.name
+ if not name:
+ raise ValueError(f"{self!r} has an empty name")
+ elif isinstance(target_dir, PathBase):
+ target = target_dir / name
+ else:
+ target = self.with_segments(target_dir, name)
+ return self.copy(target, follow_symlinks=follow_symlinks,
+ dirs_exist_ok=dirs_exist_ok,
+ preserve_metadata=preserve_metadata, ignore=ignore,
+ on_error=on_error)
+
def rename(self, target):
"""
Rename this path to the target path.
@@ -947,6 +965,19 @@ class PathBase(PurePathBase):
self.delete()
return target
+ def move_into(self, target_dir):
+ """
+ Move this file or directory tree into the given existing directory.
+ """
+ name = self.name
+ if not name:
+ raise ValueError(f"{self!r} has an empty name")
+ elif isinstance(target_dir, PathBase):
+ target = target_dir / name
+ else:
+ target = self.with_segments(target_dir, name)
+ return self.move(target)
+
def chmod(self, mode, *, follow_symlinks=True):
"""
Change the permissions of the path, like os.chmod().