Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/pathlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,25 @@ def __ge__(self, other):
return NotImplemented
return self._parts_normcase >= other._parts_normcase

@property
def name(self):
"""The final path component, if any."""
tail = self._tail
if not tail:
return ''
return tail[-1]

def with_name(self, name):
"""Return a new path with the file name changed."""
m = self.pathmod
if not name or m.sep in name or (m.altsep and m.altsep in name) or name == '.':
raise ValueError(f"Invalid name {name!r}")
tail = self._tail.copy()
if not tail:
raise ValueError(f"{self!r} has an empty name")
tail[-1] = name
return self._from_parsed_parts(self.drive, self.root, tail)

def relative_to(self, other, /, *_deprecated, walk_up=False):
"""Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
Expand Down
13 changes: 6 additions & 7 deletions Lib/pathlib/_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,10 +313,10 @@ def anchor(self):
@property
def name(self):
"""The final path component, if any."""
tail = self._tail
if not tail:
path_str = str(self)
if not path_str or path_str == '.':
return ''
return tail[-1]
return self.pathmod.basename(path_str)

@property
def suffix(self):
Expand Down Expand Up @@ -360,11 +360,10 @@ def with_name(self, name):
m = self.pathmod
if not name or m.sep in name or (m.altsep and m.altsep in name) or name == '.':
raise ValueError(f"Invalid name {name!r}")
tail = self._tail.copy()
if not tail:
parent, old_name = m.split(str(self))
if not old_name or old_name == '.':
raise ValueError(f"{self!r} has an empty name")
tail[-1] = name
return self._from_parsed_parts(self.drive, self.root, tail)
return self.with_segments(parent, name)

def with_stem(self, stem):
"""Return a new path with the stem changed."""
Expand Down