@@ -400,13 +400,14 @@ def stem(self):
400
400
401
401
def with_name (self , name ):
402
402
"""Return a new path with the file name changed."""
403
- if not self .name :
404
- raise ValueError ("%r has an empty name" % (self ,))
405
403
m = self .pathmod
406
404
if not name or m .sep in name or (m .altsep and m .altsep in name ) or name == '.' :
407
- raise ValueError ("Invalid name %r" % (name ))
408
- return self ._from_parsed_parts (self .drive , self .root ,
409
- self ._tail [:- 1 ] + [name ])
405
+ raise ValueError (f"Invalid name { name !r} " )
406
+ tail = self ._tail .copy ()
407
+ if not tail :
408
+ raise ValueError (f"{ self !r} has an empty name" )
409
+ tail [- 1 ] = name
410
+ return self ._from_parsed_parts (self .drive , self .root , tail )
410
411
411
412
def with_stem (self , stem ):
412
413
"""Return a new path with the stem changed."""
@@ -417,21 +418,12 @@ def with_suffix(self, suffix):
417
418
has no suffix, add given suffix. If the given suffix is an empty
418
419
string, remove the suffix from the path.
419
420
"""
420
- m = self .pathmod
421
- if m .sep in suffix or m .altsep and m .altsep in suffix :
422
- raise ValueError ("Invalid suffix %r" % (suffix ,))
423
- if suffix and not suffix .startswith ('.' ) or suffix == '.' :
424
- raise ValueError ("Invalid suffix %r" % (suffix ))
425
- name = self .name
426
- if not name :
427
- raise ValueError ("%r has an empty name" % (self ,))
428
- old_suffix = self .suffix
429
- if not old_suffix :
430
- name = name + suffix
421
+ if not suffix :
422
+ return self .with_name (self .stem )
423
+ elif suffix .startswith ('.' ) and len (suffix ) > 1 :
424
+ return self .with_name (self .stem + suffix )
431
425
else :
432
- name = name [:- len (old_suffix )] + suffix
433
- return self ._from_parsed_parts (self .drive , self .root ,
434
- self ._tail [:- 1 ] + [name ])
426
+ raise ValueError (f"Invalid suffix { suffix !r} " )
435
427
436
428
def relative_to (self , other , / , * _deprecated , walk_up = False ):
437
429
"""Return the relative path to another path identified by the passed
@@ -1029,7 +1021,7 @@ def _glob(self, pattern, case_sensitive, follow_symlinks):
1029
1021
elif not path_pattern ._tail :
1030
1022
raise ValueError ("Unacceptable pattern: {!r}" .format (pattern ))
1031
1023
1032
- pattern_parts = list ( path_pattern ._tail )
1024
+ pattern_parts = path_pattern ._tail . copy ( )
1033
1025
if pattern [- 1 ] in (self .pathmod .sep , self .pathmod .altsep ):
1034
1026
# GH-65238: pathlib doesn't preserve trailing slash. Add it back.
1035
1027
pattern_parts .append ('' )
0 commit comments