Sub topic 5
Deriving new paths: with_name, with_suffix, relative_to
This chapter assumes you can build a Path with the / operator and read its attributes (name, stem, suffix, parent, parts). Those are covered in the two previous chapters. Here you will use those attributes to produce new paths, such as an output file next to an input file or a path inside a mirrored directory tree.
Derived paths are new objects
A Path is immutable. Every method in this chapter returns a new Path and leaves the original unchanged. None of them touch the file system. with_name does not rename a file, and relative_to does not check that the file exists. They only do text-level work on the path's parts. Actual renaming comes in a later chapter.
| Method | What it replaces or does | Python version |
|---|---|---|
| `with_name(name)` | the last component, including its extension | 3.4+ |
| `with_stem(stem)` | the last component, keeping the current suffix | 3.9+ |
| `with_suffix(suffix)` | the last extension only | 3.4+ |
| `relative_to(other)` | strips a leading prefix | 3.4+ |
| `is_relative_to(other)` | tests whether that prefix applies | 3.9+ |
Replacing the name
with_name swaps the final component. with_stem swaps only the part before the last dot.
from pathlib import Path
p = Path("data/reports/summary.csv")
print(p.with_name("totals.csv")) # data/reports/totals.csv
print(p.with_stem("totals")) # data/reports/totals.csv
print(p.name) # summary.csv (the original is unchanged)On Windows the separators print as backslashes. The examples show POSIX output.
with_name raises ValueError in three cases:
- The path has no name, as with
Path("/")orPath(""). - The new name is empty.
- The new name contains a separator.
from pathlib import Path
for make in (
lambda: Path("/").with_name("x"),
lambda: Path("a.txt").with_name(""),
lambda: Path("a.txt").with_name("sub/b.txt"),
):
try:
make()
except ValueError as exc:
print("ValueError:", exc)The separator rule is useful. with_name can never move a file into another directory, so a user-supplied name cannot silently escape the parent. If you do want a different directory, use p.parent / "other" / p.name.
Replacing the suffix
with_suffix changes the extension, and it replaces only the last one.
from pathlib import Path
draft = Path("notes/draft.txt")
print(draft.with_suffix(".md")) # notes/draft.md
print(draft.with_suffix("")) # notes/draft (removes the suffix)
archive = Path("backups/site.tar.gz")
print(archive.with_suffix(".zip")) # backups/site.tar.zipThe last line is a common surprise. .gz is the only suffix with_suffix sees, so the result is site.tar.zip, which is rarely what you want. When a file has a compound extension, strip it explicitly and use with_name:
from pathlib import Path
archive = Path("backups/site.tar.gz")
base = archive.name.removesuffix(".tar.gz") # str.removesuffix needs 3.9+
print(archive.with_name(base + ".zip")) # backups/site.zipSuffix rules to remember:
- The new suffix must start with a dot, so
with_suffix("md")raisesValueError. - A lone
"."is also invalid. - Hidden files such as
.bashrchave no suffix, because the leading dot belongs to the name.Path(".bashrc").with_suffix(".bak")gives.bashrc.bak. - If the path has no name,
with_suffixraisesValueError, aswith_namedoes.
Making a path relative
relative_to removes a leading prefix and returns what remains. This is how you turn an absolute path into one that is relative to a project root, for display or for storing in a manifest.
from pathlib import Path
root = Path("/srv/app")
log = Path("/srv/app/logs/app.log")
print(log.relative_to(root)) # logs/app.log
print(log.is_relative_to(root)) # True
print(root.relative_to(root)) # . (an empty relative path)If the path is not under the prefix, relative_to raises ValueError. Use is_relative_to to test first, or catch the exception:
from pathlib import Path
root = Path("/srv/app")
other = Path("/srv/other/x.log")
if other.is_relative_to(root):
print(other.relative_to(root))
else:
print("outside the root") # outside the rootOn Python 3.12 and later, relative_to accepts walk_up=True, which inserts .. segments when the target is not under the prefix:
from pathlib import PurePosixPath
target = PurePosixPath("/srv/app/x.txt")
print(target.relative_to("/srv/other", walk_up=True)) # ../app/x.txtOn older versions, os.path.relpath gives the same result. It takes strings, so wrap the arguments in str() or pass the Path objects directly, since it accepts path-like objects.
A safe containment check therefore looks like this:
from pathlib import Path
def is_inside(child: Path, root: Path) -> bool:
return child.resolve().is_relative_to(root.resolve())
print(is_inside(Path("/srv/app/../secret"), Path("/srv/app"))) # Falseresolve() is covered in the next chapter. For now, treat it as "make absolute and clean up .. and symlinks".
Two more rules for relative_to:
- Both paths must be the same kind. An absolute path cannot be made relative to a relative path, and the reverse also fails with
ValueError. - The comparison works on whole segments.
/srv/applicationis not under/srv/app, even though the strings share a prefix. This is an advantage overstr.startswith.
Combining the methods
The methods compose because each returns a Path. A typical task is to mirror a source tree into an output tree and change the extension on the way:
from pathlib import PurePosixPath
def output_for(src, src_root, out_root):
relative = src.relative_to(src_root)
return (out_root / relative).with_suffix(".html")
src_root = PurePosixPath("/project/docs")
out_root = PurePosixPath("/project/site")
for name in ("index.md", "guide/setup.md", "guide/faq.md"):
src = src_root / name
print(src, "->", output_for(src, src_root, out_root))The output is:
/project/docs/index.md -> /project/site/index.html
/project/docs/guide/setup.md -> /project/site/guide/setup.html
/project/docs/guide/faq.md -> /project/site/guide/faq.htmlThe pipeline has three steps: strip the source root, join onto the output root, then swap the suffix. The code uses PurePosixPath so the output is the same on every system. With concrete Path objects the code works the same way, except that the separators match your operating system. When you actually write each file, create output.parent first with mkdir(parents=True, exist_ok=True).
Edge cases and failure modes
- Trailing separators are ignored.
Path("a/b/")is the same asPath("a/b"), sowith_namereplacesb, not an empty component. - Case sensitivity follows the flavor. On Windows,
relative_tocompares segments case-insensitively. On POSIX it is case-sensitive. - Dots inside names.
Path("v1.2.notes").with_suffix(".md")givesv1.2.md, because.notescounts as the suffix. Checkp.suffixbefore swapping if names may contain dots that are not extensions. - Errors are
ValueError. The same exception type covers bad names, bad suffixes, and non-matching prefixes. Catch it narrowly around the one call that can raise it. - No existence guarantee. A derived path can point at a file that does not exist. Use
exists()before reading, which is the topic of a later chapter.
Exercise
Given log = Path("/var/app/logs/2026/errors.log.gz") and root = Path("/var/app"), write code that prints the path "archive/logs/2026/errors.log" (relative to root, placed under a folder called "archive", with the .gz suffix removed). What does with_suffix("") return for a path like "logs/2026/errors.log.gz", and why is it enough here?
Show answer
Use print(Path("archive") / log.relative_to(root).with_suffix("")). relativeto(root) gives logs/2026/errors.log.gz. withsuffix("") removes only the last suffix, .gz, which returns logs/2026/errors.log. Joining it onto Path("archive") gives archive/logs/2026/errors.log. Removing just one suffix is what we want here, because .log should stay. If the file had been errors.tar.gz and we wanted to drop both, we would need with_name with removesuffix instead.